Sunday, October 30, 2005

overlaoding the << operator

Overloading the “<< operator”

 

 

#include <iostream>

#include <cstdlib>

 

using namespace std;

 

template<class Outer, class TypesystemHook>

class Target

{

    Outer& _outer;

public:

    Target( Outer& outer ) : _outer( outer ) {}

    Outer& operator()( void ) { return _outer; }

};

 

class MyClass

{

public:

 

    MyClass() : average(*this), sum(*this)

    {

        for( unsigned int i = 0; i < DataSize; i++ ) { _data[i] =

rand()%20; }

    }

 

    Target<MyClass, class Average {}> average;

    friend ostream& operator<<( ostream& os, Target<MyClass,Average>& t

)

    {

        return os << static_cast<double>( t().getSum() ) / DataSize;

    }

 

    Target<MyClass, class Sum {}> sum;

    friend ostream& operator<<( ostream& os, Target<MyClass,Sum>& t )

    {

        return os << t().getSum();

    }

 

private:

    static const unsigned int DataSize = 10;

    int _data[DataSize];

 

    int getSum() // helper

    {

        int sum = 0;

        for( unsigned int i = 0; i < DataSize; i++ ) { sum += _data[i];

}

        return sum;

    }

};

 

int main( int argc, char* argv[] )

{

    MyClass instance;

 

    cout << instance.sum << endl;

    cout << instance.average << endl;

 

    return 0;

}

 

 

 

Pradyut
http://pradyut.tk
http://spaces.msn.com/members/oop-edge/
http://groups-beta.google.com/group/oop_programming
India

 

No comments: