当 RHS 具有多个字符串或字符时,C++11 += 运算符不起作用

C++11 += operator not working when RHS has more than one string or character

我正在使用 c++11。当我使用 += 运算符连接字符串或字符时,它不起作用,但是 = 有效。

例如我独立使用了以下所有测试用例,即分别使用。

    string s="abdddddd";
    string ss="";
    ss+=s[0];//working
    ss+=s[0]+s[1]; //not working     output: Ã
    ss+="hi"+s[2];  //not working      no output
    ss+='d'+'c';  //not working      output: З
    ss+="hi"+"string"; //not working  error: invalid operands of types ‘const char [3]’ and ‘const char [7]’ to binary ‘operator+’

    string another="this";
    ss+=another+'b'; //working
    ss+="hi"+another;//working
    ss+=("hi"+s[3]); //not working
    ss=ss+"hi"+s[3]; //working
    ss=ss+"hi"+"this"; //working

添加括号也不起作用。所以,我想知道为什么它不适用于字符串,它适用于添加整数。

你的问题不是+=,而是+

例如在行ss+=s[0]+s[1];中,s[0]s[1]的类型是char。添加它们将添加它们的整数表示(ASCII 代码)并将此总和表示的字符连接到 ss.

您在 ss+='d'+'c'; 中看到了同样的情况,您在其中明确给出了 char 文字。

仅使用 +std::stringstd::string 或一个 std::string 与字符或字符串文字连接起来。您不能连接两个字符串文字或两个字符或一个字符串文字与一个字符。 (在所有这些情况下,+ 具有与字符串连接不同的语义,甚至不是有效语法。)