您能从加速c ++向我解释练习1-2吗?
int main()
{
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
std::cout << message << std::endl;
}
为什么这是不正确的?用“ Hello”更改变量可以正常工作。
是因为运算符+是右关联的吗?
的关联性operator+
是从左到右。然后"Hello" + ", world" + exclam
被解释为("Hello" + ", world") + exclam
while"Hello" + ", world"
无效。"Hello"
并且", world"
是const char[]
s,并且可能会衰减到const char*
无法添加的指针。
使用std::string
的,而不是C风格的字符串或代码更改为"Hello" + (", world" + exclam)
作品,因为有operator+
对std::string
可能接受两个std::string
S或Astd::string
和C风格的字符串(作为第一或第二个操作数),它的回报std::string
可能进一步增加。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句