2011-01-31 73 views
4

我有串轉換操作符類的Foobar:不匹配 '運算符<<' 中的std ::運營商<< [隨着_Traits =標準:: char_traits <char>]

#include <string> 

class Foobar 
{ 
public: 
    Foobar(); 
    Foobar(const Foobar&); 
    ~Foobar(); 

    operator std::string() const; 
}; 

我嘗試使用它像這樣:

// C++源文件

#include <iostream> 
#include <sstream> 
#include "Foobar.hpp" 

int main() 
{ 
    Foobar fb; 
    std::stringstream ss; 

    ss << "Foobar is: " << fb; // Error occurs here 

    std::cout << ss.str(); 
} 

我需要明確的創建操作< <爲Foobar的?我不明白爲什麼這是必要的,因爲FooBar在被放入iostream之前被轉換爲字符串,並且std :: string已經定義了運算符< <。

那麼爲什麼這個錯誤呢?我錯過了什麼?

[編輯]

我發現,如果我改了行發生錯誤的情況,這樣:

ss << "Foobar is: " << fb.operator std::string(); 

它編譯成功。呃......!爲什麼編譯器不能自動轉換(Foobar - > string)?

什麼是解決這個問題的「最佳實踐」方法,所以我不必使用上面醜陋的語法?

+0

http://stackoverflow.com/q/6677072/560648? – 2014-06-08 18:20:27

回答

6

在放入流中之前,Foobar fb未轉換爲字符串。不要求運算符的參數必須是字符串。

您應該將它轉換爲字符串手動

ss << "Foobar is: " << std::string(fb); 

或定義操作< <爲Foobar的。

定義一個運營商< <將是明智的選擇,並且沒有理由不能在您的運營商< <代碼中調用您的字符串轉換。