簡體   English   中英

為什么“+=”運算符在添加多個字符串時不起作用?

[英]Why "+=" operator not works when more than one string is added?

當我嘗試使用此運算符 (+=) 連接一個字符串變量與多個字符串時,它會引發錯誤。

注意:其他兩個字符串不應存儲在變量中。

string str="hello";
    
str = str + " " + "world";
cout << str << endl;    //hello world
    
str += " " + "world";
cout << str;            //error              //why?
                        //*but in java it works*

因為您要添加兩個字符串文字。 表達方式:

" " + "world"

在 C++ 是類型

const char* + const char*

const char*沒有重載的 operator+。 但是標准字符串確實會重載 operator+ 以與字符串文字相加,例如:

operator+(std::string const& lhs, const char *rhs);

這就是您的第一個表達式成功的原因: str object 讓球滾動:

str + " " + "World" 
= std::string + const char* + const char*
= std::string + const char*
= std::string

讓它工作使用

str += " world"
// or
str += std::string(" ") + "world";
// the last one is to better explain what's going on,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM