2012-01-11 115 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