2012-01-11 114 views
8

我有下面的类(prototipe):C++的std :: stringstream的运营商<<重载

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给了我的错误,说是有敌不过< <运营商。我在错什么?

+0

欢迎SO。当您提供代码示例时,请保留一份可编译的代码。并*总是*给出完整的编译器错误。 – thiton 2012-01-12 11:11:49

回答

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

应该

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

只是一个问题,为什么ostream,而不是stringstream?由于stringstream是继承operator << from ostream?此外,是强制性的? – 2012-01-11 18:08:07

+0

@dtumaykin:'const'不是必需的,但它是很好的风格。 'ostream'是'ostringstream'和'stringstream'派生出来的输出流的类。 – 2012-01-11 18:33:36

+1

观察这里对“friend”的需求:http://stackoverflow.com/questions/15777944/overloading-the-operator-error-c2804-binary-operator-has-too-many-param – VillasV 2015-11-06 05:49:55