1

I would like to create a class similar to std::cout. I know how to overload the >> and << operators, but I would like to overload the << operator so it would be input, just like in std::cout.

it should be somthing like:

class MyClass
{
   std::string mybuff;
 public:
   //friend std::???? operator<<(????????, MyClass& myclass)
   {
   }
}
.
.
.

  MyClass class;
    class << "this should be stored in my class" << "concatenated with this" << 2 << "(too)";

Thanks

Mercury
  • 1,886
  • 5
  • 25
  • 44

2 Answers2

4
class MyClass
{
    std::string mybuff;
 public:
    //replace Whatever with what you need
    MyClass& operator << (const Whatever& whatever)
    {
       //logic
       return *this;
    }

    //example:
    MyClass& operator << (const char* whatever)
    {
       //logic
       return *this;
    }
    MyClass& operator << (int whatever)
    {
       //logic
       return *this;
    }
};
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

I think the most general answer would be:

class MyClass
{
   std::string mybuff;
 public:
   template<class Any>
   MyClass& operator<<(const Any& s)
   {
          std::stringstream strm;
          strm << s;
          mybuff += strm.str();
   }

   MyClass& operator<<( std::ostream&(*f)(std::ostream&) )
   {
    if( f == std::endl )
    {
        mybuff +='\n';
    }
    return *this;
}
}

std::endl was pasted from Timbo's answer here

Thanks for the answers!

Community
  • 1
  • 1
Mercury
  • 1,886
  • 5
  • 25
  • 44
  • (1) If you can, make `mybuff` an `ostringstream`, that way you don't need the extra concatenation in `operator<<(Any)`. (2) Your overload for stream manipulators only handles `endl`, nothing else. This means that `std::hex` or whatever can be written to the stream, but have no effect. If `mybuff` was an `ostringstream` then you could apply the manipulator to that. Then all the usual formatting options would work and so would `endl`, no need to special-case it. – Steve Jessop Jul 17 '12 at 07:13
  • Can you post how the operator<< should look like? – Mercury Jul 17 '12 at 08:07