class as cout (ostream)

I need to code a class that behaves as a cout (or is used instead of a cout). The class is constructed by getting a reference to a cout - so it would be

ClassName nam(&cout);

and then to output a string or something
nam << "output"; //prints 'output'
there are more stuff to do but I can figure that out, its just that I never programmed something similar and I cant find an example of what I am looking for...
Turns out this is a duplicated post:
http://cplusplus.com/forum/general/72700/

Well, you could have something like this for your class:

1
2
3
4
5
6
7
8
9
10
11
#include <ostream>

class MyCout
{
   std::ostream& myCoutReference;

public:
   MyCout(std::ostream& referenceToCout) : myCoutReference(referenceToCout)
   {
   }
};


Then it would all be a matter of implementing the operators listed here:
http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/

For instance:

1
2
3
4
5
MyCout& MyCout::operator<<(bool val)
{
   myCoutReference << val;
   return *this; //for concatenating calls to this operator 
}
Last edited on
Topic archived. No new replies allowed.