1

我想创建一个类似于 std::cout 的类。我知道如何重载 >> 和 << 运算符,但我想重载 << 运算符,以便它成为input,就像在 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)";

谢谢

4

2 回答 2

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;
    }
};
于 2012-07-17T06:13:09.093 回答
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 的答案粘贴在这里

感谢您的回答!

于 2012-07-17T06:40:52.247 回答