Exercise 1-2
Are the following definitionsvalid? Why or why not?
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
Solution
The first line is valid because it initializes the variable exclaim with the value "!".The second line is not valid, however. The reason is that the +operator is left-associative. This means that it is being used to concatenate "Hello"and ", world", which is not legal because one of the operands must be a std::string object. In the exercise, "Hello"and", world" are both string literals.

本文探讨了C++中使用标准库字符串进行拼接的有效性和合法性问题,特别是针对字符串常量与std::string类型的拼接操作。文章指出,直接使用+运算符连接字符串字面量与std::string对象是不合法的,并解释了原因。
631

被折叠的 条评论
为什么被折叠?



