【问题标题】:C++ std::stringstream operator<< overloadingC++ std::stringstream 运算符<< 重载
【发布时间】:2012-01-11 18:01:01
【问题描述】:

我有以下类(原型):

class Token
{
public:
    //members, etc.
    friend std::stringstream& operator<< (std::stringstream &out, Token &t);
};

而操作符是这样实现的:

std::stringstream & operator<< (std::stringstream &out, Token &t)
{
    out << t.getValue(); //class public method
    return out;
}

现在,我正在尝试这样使用它:

std::stringstream out;
Token t;
//initialization, etc.

out << t;

VS 给了我错误,说

【问题讨论】:

  • 欢迎来到 SO。当您提供代码示例时,请将它们保留为单个可编译的代码。并且总是给出完整的编译器错误。

标签: c++ overloading


【解决方案1】:
std::stringstream & operator<< (std::stringstream &out, Token &t)

应该是

std::ostream & operator<< (std::ostream &out, Token const &t)

【讨论】:

  • 只是一个问题,为什么是ostream,而不是stringstream?因为 stringstream 是从 ostream 继承 operator
  • @dtumaykin: const 不是必需的,但它的风格很好。 ostream 是输出流的类,ostringstreamstringstream 派生自。
  • 在此处观察friend 的需要:stackoverflow.com/questions/15777944/…
猜你喜欢
  • 2012-01-23
  • 1970-01-01
  • 2023-01-27
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
相关资源
最近更新 更多