C++ std::stringstream操作符<<重载

13

我有以下类(原型):

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时遇到了错误,提示没有匹配的<<运算符。我做错了什么吗?


1
欢迎来到SO。当您提供代码示例时,请确保它们是一段可编译的代码。并且*请始终提供完整的编译器错误。 - thiton
1个回答

16
std::stringstream & operator<< (std::stringstream &out, Token &t)

应该是

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

3
为什么选择ostream而不是stringstream?是因为stringstream继承了ostream的operator<<吗?同时,const是否是必须的? - Dan Tumaykin
@dtumaykin:const并非必需,但是它是良好的编程风格。ostream是输出流的类,ostringstreamstringstream都是它的派生类。 - Fred Foo
2
请注意这里需要使用 friend:https://dev59.com/dnDYa4cB1Zd3GeqPAXJ0 - villasv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接