2010-02-24 103 views
14
#include <iostream> 


int main() 
{ 
    const std::string exclam = "!"; 
    const std::string message = "Hello" + ", world" + exclam; 
    std::cout << message; 
    return 0; 
} 

爲什麼此代碼不起作用?錯誤返回:無法在C++中添加字符串

error: invalid operands of types `const char[6]' and `const char[8]' to binary `operator+' 

在此先感謝!

編輯:

感謝您的所有答案。這是我第一次在這個網站上,我很驚訝於在這麼短的時間內詳細解釋的數量。

關於實際問題。那麼這是怎麼來的呢:

const std::string hello = "Hello"; 
const std::string message = hello + ", world" + "!"; 

是因爲「,世界」以及之後的「!」與變量hello(已定義)連接?

+0

爲什麼不這樣做: const std :: string message =「Hello,world」+ exclam; – 2010-02-24 21:32:06

+0

歡迎來到本網站!只是供參考,如果有你喜歡的答案,確保你接受它。你更有可能在未來獲得幫助。 – JasCav 2010-02-24 21:44:28

回答

18

因爲在C++中,字符串(如"Hello"std::string類型不。他們是普通的字符數組或C風格的字符串。

所以對於線const std::string message = "Hello" + ", world" + exclam;,編譯器有很多與工作的類型:

const std::string message = const char[6] + const char[8] + std::string;

,並給出了+的關聯性,它必須執行的操作是:

const std::string message = ((const char[6] + const char[8]) + std::string);

也就是說,必須先評估最左邊的加法,然後將結果傳遞給最右邊的加法。

所以編譯器試圖評估const char[6] + const char[8]。 沒有爲陣列定義添加項。數組隱式轉換爲指針,但這對編譯器沒有幫助。這只是意味着它結束了const char* + const char*,並且也沒有爲指針定義添加。

此時,它不知道要將結果轉換爲std::string

然而,在你的第二個例子:

const std::string hello = "Hello"; 
const std::string message = hello + ", world" + "!"; 

它的工作,因爲運作的編譯器會看到是std::string + const char[8] + const char[2]。這裏,第一個加法可以轉換爲std::string + const char*,這裏加法運算符定義爲,並返回std::string。所以編譯器已經成功地算出了第一個加法,並且由於結果是一個字符串,第二個加法看起來像這樣:std::string + const char[2],和以前一樣,這是不可能的,但是數組可以被轉換爲一個指針,然後編譯器能夠找到一個可以運行的加法運算符,再次導致std::string

+5

+1,@jalf - 出色的答案 – 2010-02-24 21:53:56

4

在形成消息的行中,首先執行=右邊的整個表達式,然後纔將其分配給C++字符串。此時,你的「你好」和你的「世界」仍然是C字符串(const char []),這就是你出錯的原因。加法從左到右,因此在嘗試將組合添加到std :: string exclam之前,會添加一對C字符串。您需要將它們轉換爲表達式(例如,std :: string(「Hello」)),或者爲每個類型創建字符串變量,就像您使用Exclam所做的一樣。

15
"Hello" + ", world" 

由於這些都是c風格的字符串,所以不能附加+。您可以將std :: string附加到c樣式的字符串中,但不是以這種方式添加2個c樣式的字符串,而是在其中一個std :: string()構造函數週圍添加一個臨時的字符串,即:

"Hello" + std::string(", world") 
+4

他也可以在''Hello「'和'」world「之間省略'+'運算符,例如: const std :: string message =」Hello「」world「+ exclam;' 這是也是連接字符串文字的一種可接受的方式。 – fogo 2010-02-24 21:31:21

4

字符串文字在C++中只是零終止的字符數組。沒有運算符允許您在C++中添加2個字符數組。

然而,有一個char數組和std :: string +運算符。

更改爲:

const std::string message = std::string("Hello") +", world" + exclam; 

在像Python字符串文字有些語言等同於類型的字符串變量。 C++不是這樣一種語言。

6

C++不會執行許多其他面嚮對象語言的自動'幕後'對話。由於Doug說你需要做std :: string(「hello」)+ std :: string(「world」),所以語言不會爲你做這件事。

但是你可以做

std::cout << "hello" << "world" << exclam; 

因爲性病::法院知道如何打印一個const char [],以及作爲一個字符串

3

C風格的字符串(「你好」和」世界「)相當於匿名陣列:

static const char anon1[6] = { 'H', 'e', 'l', 'l', 'o', '\0' }; 
static const char anon2[8] = { ',', ' ', 'w', 'o', 'r', 'l', 'd', '\0' }; 

...所以當你輸入"Hello" + ", world"時,你試圖添加兩個不是C或C++支持的操作的數組anon1 + anon2。請記住,C/C++中的字符串文字只是數組(或數組的地址)。您必須使用字符串類(例如std:string)才能使用像+這樣的運算符。