【问题标题】:overloading operator >> like std::cout重载运算符 >> 像 std::cout
【发布时间】:2012-07-17 06:12:32
【问题描述】:

我想创建一个类似于 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)";

谢谢

【问题讨论】:

标签: c++


【解决方案1】:
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;
    }
};

【讨论】:

  • 我已经尝试过了,但我收到以下错误:错误 C2679:二进制“
  • @Mercury 你用const char*替换了Whatever吗?
  • @Mercury 也看看std::stringstream,它也可以连接。
【解决方案2】:

我认为最普遍的答案是:

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

感谢您的回答!

【讨论】:

  • (1) 如果可以,请将mybuff 设为ostringstream,这样就不需要operator&lt;&lt;(Any) 中的额外连接。 (2) 您对流操纵器的重载仅处理 endl,仅此而已。这意味着std::hex 或任何可以写入流的内容,但没有效果。如果mybuff 是ostringstream,那么您可以将操纵器应用于它。然后所有常用的格式化选项都可以使用,endl 也可以使用,无需特殊处理。
  • 你能发布操作符
猜你喜欢
  • 2020-01-25
  • 1970-01-01
  • 2011-09-30
  • 1970-01-01
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多