您能从加速c++向我解释练习1-2吗?
int main()
{
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
std::cout << message << std::endl;
}
为什么这是不正确的?
用“Hello”更改变量可以正常工作。
是因为运算符+是右关联的吗?
最佳答案
operator+
的associativity从左到右。然后"Hello" + ", world" + exclam
解释为("Hello" + ", world") + exclam
,而"Hello" + ", world"
无效。 "Hello"
和", world"
是const char[]
,可能会衰减为无法添加的const char*
指针。
使用std::string
而不是c样式的字符串,或将代码更改为"Hello" + (", world" + exclam)
的方法是可行的,因为存在 operator+
for std::string
可以接受两个std::string
s或std::string
和一个c样式的字符串(作为第一个或第二个操作数),并且它返回std::string
进一步添加。
关于c++ - C++中字符串的加号运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61727262/