简体   繁体   中英

overloading operator >> like std::cout

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

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;
    }
};

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM