+ =使用C++中的字符串

Mih*_*csu 0 c++ string

我正在玩C++中的字符串,我不明白为什么以下在编译时会导致错误:

string s = "hi";
s += " " + "there!";
Run Code Online (Sandbox Code Playgroud)

错误信息:

error: invalid operands of types ‘const char [2]’ and ‘const char [6]’ to binary ‘operator+’
Run Code Online (Sandbox Code Playgroud)

我也试过s+= (" " + "there!");,它也不起作用.

为什么我不能使用二元运算符+=以这种方式连接字符串?

Joh*_*nck 10

问题是你试图"添加"两个文字字符串.文字字符串不是C++中的std :: string类型,它们就像不可变的字符数组.将两个加在一起没有意义,因为它就像将两个指针放在一起一样.

但是,您可以这样做:

std::string("foo") + "bar"
Run Code Online (Sandbox Code Playgroud)

这是因为在C++中定义了一些方法来将C++字符串与C字符串连接起来.


Mar*_*som 9

文字字符串不是字符串对象,它们只是字符数组.当你尝试像这样添加它们时,它们会衰变成指向数组的指针 - 而且你不能添加一对指针.如果将第一个文字转换为字符串对象,它将按预期工作.

s += string(" ") + "there!";
Run Code Online (Sandbox Code Playgroud)

您也可以通过将它们放在一起而不使用它来连接文字+.

s += " "  "there!";
Run Code Online (Sandbox Code Playgroud)