我是C++的新手,我指的是Accelerated C++。雖然嘗試的行使問題,其中一個說:在C++中使用「+」連接字符串
Are the following definitions valid? Why or why not?
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
,當我試圖&執行的程序我得到一個錯誤:類型爲二進制運算符+
無效操作數。
但是,下面的代碼工作完全正常:
const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";
我不是它的執行清楚!爲什麼這種連接在第一種情況下不起作用?
謝謝!我正在使用DEV C++。
爲'std :: string'重載'+'(這就是第二個例子的原因)。第一個例子是試圖對兩個字符串文字('「Hello」'和'「,world」'不是'std :: string'對象)使用'+'。 – birryree
下面的答案解釋了代碼不起作用的原因;我添加了另一種修復代碼的方式。您可以通過添加圓括號來改變操作順序,以確保所有連接都調用了std :: string :: operator +'。 'const std :: string message =「Hello」+(「,world」+ exclam);'但是在這種情況下,最好通過簡單地除去它們之間的'+'來連接文字。 – Praetorian