简体   繁体   English

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

[英]overloading operator >> like std::cout

I would like to create a class similar to std::cout. 我想创建一个类似于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. 我知道如何重载>>和<<运算符,但我想重载<<运算符,因此它将被输入 ,就像在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 std :: endl在这里粘贴了Timbo的答案

Thanks for the answers! 谢谢你的回答!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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