2016-09-20 61 views
3

我有問題在屏幕上打印文本。我雖然沒有有效的「+」運算符用於流出文本。這是爲什麼一個有效的:使用「<<」時「+」運算符的有效性

std::cout << ("print this number " + boost::lexical_cast<std::string>(5) + ". ") << std::endl; 

雖然存在用於此complie錯誤:

std::cout << ("print this number " + "5" + ". ") << std::endl; 

錯誤:類型的無效操作數 '爲const char [19]' 和 '爲const char [2]' 至二進制'運算符+'

我使用gcc 4.7.3和C++ 03。

+0

如果使用字符串對象,則使用'+'運算符。請注意括號 – Hayt

+0

'運算符+'用於'std :: string:'在此處使用。哪裏不對? – ilotXXI

回答

6

boost::lexical_cast返回std::string其中operator +(const char *, const std::string&)operator +(const std::string&, const char *)定義它。

std::cout << std::string("print this number 5. ") << std::endl; 

沒有與std::ostream沒有參數的operator +調用:所以你的代碼獲取等同。

在第二行中,嘗試添加字符數組(例如const char [19]const char [2]),這是語言規則的錯誤。

0

很明顯,+是在<<之前執行的 - 單獨執行括號。運算符+適用於它周圍的字符串,爲什麼它不起作用?

3

這是因爲首先評估括號內的表達式。

類型boost::lexical_cast<std::string>(5)std::string。這已經超過+運營商爲const char*(在兩邊),這返回std::string

所以在括號中的表達式的類型std::string,並且流具有一個重載<<它。

最後"print this number " + "5" + ". "將無法​​編譯,因爲+const char[]爭論沒有意義,即使他們衰減到指針類型。

0

這與流媒體沒有任何關係。這只是關於"print this number " + boost::lexical_cast<std::string>(5) + ". " vs "print this number " + "5" + ". "的有效性。

第一部分工作的原因是第二部分是std::string,而不是字符串文字。運算符+用於連接std::string,或者將字符串對象和字符串文字(C樣式字符串)混合使用,但不適用於第二個表達式中的純C類型字符串。