[英]C++11 += operator not working when RHS has more than one string or character
I am using c++11
.我正在使用
c++11
。 When I use the +=
operator for concating strings or characters, it does not work, however =
, works.当我使用
+=
运算符连接字符串或字符时,它不起作用,但是=
起作用。
eg I used all the below test cases independently, ie separately.例如,我独立使用了以下所有测试用例,即分别使用。
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
Also adding brackets doesn't work.添加括号也不起作用。 So, I want to know why it doesn't work with strings, it works with adding integers.
所以,我想知道为什么它不适用于字符串,它适用于添加整数。
Your problem is not +=
, it is +
.您的问题不是
+=
,而是+
。
For example in the line ss+=s[0]+s[1];
例如在行
ss+=s[0]+s[1];
, s[0]
and s[1]
are of type char
. ,
s[0]
和s[1]
是char
类型。 Adding them will add their integer representations (ASCII codes) and concatenate the character this sum represents to ss
.添加它们将添加它们的 integer 表示(ASCII 代码)并将此总和表示的字符连接到
ss
。
You see the same happing in ss+='d'+'c';
你会在
ss+='d'+'c';
中看到同样的情况。 , where you are giving char
literals explicitly. ,您在其中明确给出
char
文字。
Only use +
to concatenate std::string
with std::string
or one std::string
with a character or string literal.仅使用
+
将std::string
与std::string
或一个std::string
与字符或字符串文字连接。 You cannot concatenate two string literals or two characters or a string literal with a character.您不能将两个字符串文字或两个字符或字符串文字与一个字符连接起来。 (In all of these cases
+
has different semantics than string concatenation or isn't even valid syntax.) (在所有这些情况下,
+
的语义与字符串连接不同,甚至不是有效的语法。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.