重载运算符>>像std :: cout

时间:2012-07-17 06:12:32

标签: c++

我想创建一个类似于std :: cout的类。我知道如何重载>>和<<运营商,但我想重载<<运算符所以它将是输入,就像在std :: cout中一样。

应该是这样的:

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)";

由于

2 个答案:

答案 0 :(得分: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;
    }
};

答案 1 :(得分:0)

我认为最常见的答案是:

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是从Timbo的回答here

中粘贴的

感谢您的回答!