我是新的C++,我遇到了這個怪胎與常量的std :: string分配C++,如果右手邊包含字符串字面串聯常量的std :: string分配錯誤
這工作得很好: 常量的std ::字符串hello =「你好」; const std :: string message = hello +「world」;
這給編譯器錯誤: const std :: string message =「Hello」+「world」;
我不明白爲什麼這是任何人?
由於
我是新的C++,我遇到了這個怪胎與常量的std :: string分配C++,如果右手邊包含字符串字面串聯常量的std :: string分配錯誤
這工作得很好: 常量的std ::字符串hello =「你好」; const std :: string message = hello +「world」;
這給編譯器錯誤: const std :: string message =「Hello」+「world」;
我不明白爲什麼這是任何人?
由於
沒有operator +
定義的取const char*
類型的兩個指針,並返回包含它們指向的字符串的連接字符的一個新的數組。
你可以做的是:
std::string message = std::string("Hello") + "world";
甚至:
std::string message = "Hello" + std::string("world");
要連接文本字符串,你不需要把他們之間的額外+
,只是把它們放在一起,沒有任何運算符將執行級聯:
std::string message = "Hello" "world";
printf("%s\n", message.c_str());
和上面的代碼會給你:
Helloworld
爲了迂迴,它們不是'const char *',它們是'const char [6]'和'const char [7]'。 –
@JesseGood:確實,字符串文字是數組。但是,當作爲參數傳遞給運算符重載時,它們會不會衰變爲指針? –
是的,當傳遞給過載時,do衰減爲const char *'。因爲沒有超載,所以我想''你好「+」世界「的類型,但讀過你說的話,這是不正確的(抱歉的噪音:))。 –