我试图将两个字母附加到一个字符串,但似乎该字符串没有改变:
void fun()
{
string str;
str += 'a' + 'b';
cout << str;
}
我查看了STL的源代码,找到了实现operator+=
,但我仍然不知道为什么。
basic_string&
operator+=(_CharT __c)
{
this->push_back(__c);
return *this;
}
通过添加'a' + 'b'
,您将有 2 个字符加在一起形成另一个字符。然后用 . 将它添加到字符串中+=
。
此代码将执行您想要的操作:
std::string str;
( str += 'a' ) += 'b';
std::cout << str;
你没有在这里使用字符串。要么使用显式强制转换。或者将其声明为字符串变量。
例如:
void fun()
{
string str, str1 = 'a', str2 ='b';
str += str1 + str2
cout << str;
}
或者
void fun()
{
string str;
str += string("a") + 'b';
cout << str;
}
str += 'a' + 'b'; when run this, the single operator '+' is prior to complex operator '+=', so first it calculate the sum of two char symbols, and the sum result is 195(ASCII value of 'a' is 97, 'b' is 98), then run the overload operator '+' of class string. trace into the function, you will find it's only accept argument of char, so it translate into a char with value of -61 (195-256==-61). but it's unprinted symbol, so the result is 0 by the end. of course, you can't get a new string by your desing.
you can recode like this:
string str;
str += 'a';
str += 'b';