c++ - 了解 C++ 字符串连接

标签 c++ string concatenation string-concatenation

<分区>

在 C++ 中,我试图理解为什么在构造这样的字符串时不会出现错误:

const string hello = "Hello";
const string message = hello + ", world" + "!";

但是你会得到一个编译时错误:

const string exclam = "!";
const string msg =  "Hello" + ", world" + exclam

编译时错误是:

main.cpp:10:33: error: invalid operands of types ‘const char [6]’ and 
‘const char [8]’ to binary ‘operator+’

为什么第一次运行正常但第二次产生编译时错误?

最佳答案

写出来会更有意义:

hello + ", world"+ "!"; 看起来像这样:

operator+(operator+(hello, ", world"), "!");

同时

"Hello"+ ", world"+ exclam 看起来像这样

operator+(operator+("Hello" , ", world"), exclam);

由于没有接受两个 const char 数组的 operator+,因此代码失败。

但是,不需要一个,因为您可以像下面这样连接它们(请注意,我只是删除了 + 符号):

const string msg =  "Hello" ", world" + exclam

关于c++ - 了解 C++ 字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18797961/

相关文章:

c++奇怪的std::cout行为使用指针

c++ - 用cocos2d-x绘制平滑的贝塞尔曲线

c - 如何在没有 strtok 的情况下分割字符串?

mysql - 使用 MEDIUMTEXT 和页面的 mySQL 中的数据丢失

python - tensorflow 中的字符串连接

c++ - 退出应用程序前关闭线程

c++ - cv::Mat GREY 到 RGBA 并转换为 UIImage

ios - 如何删除字符串中的 1 个组件? swift

Swift 3 隐式解包选项导致错误的字符串插值

javascript - 如何通过引用查找数组元素以便将数组与 typescript 合并?