c++ - C++中字符串的加号运算符

标签 c++ string

您能从加速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/

相关文章:

c++ - 如何解析函数及其参数

c++ - OpenCV 函数合并 Mat 的黑色/透明像素除外

c++ - 多行字符串初始化

java - 替换字符串中的提及

c++ - 无符号字符串构造不可能

python - 从长度到起始索引切片

c++ - OpenCVs LineIterator 在 MATLAB 中的等价物

c++ - 无法将 FindFileData.cFileName 转换为字符串

c++ - 使用小数组制作长 vector (列矩阵)

c++ - 将 std::string 传递给函数 f(**char)