【发布时间】:2013-05-10 07:08:50
【问题描述】:
我是 C++ 新手,我指的是 Accelerated C++。在尝试其中一个练习题时:
Are the following definitions valid? Why or why not?
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
当我尝试并执行程序时,我收到一个错误:
二元运算符 + 的类型操作数无效。
但是下面的代码工作得很好:
const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";
我不清楚它的执行!为什么这种串联在第一种情况下不起作用?
谢谢!我正在使用 DEV C++。
【问题讨论】:
-
+为std::string重载(这就是第二个示例有效的原因)。第一个例子是尝试在两个字符串文字上使用+("Hello"和", world"不是std::string对象)。 -
下面的答案解释了为什么代码不起作用;我正在添加另一种修复代码的方法。您可以通过添加括号来更改操作顺序,以确保所有连接都调用
std::string::operator+。const std::string message = "Hello" + (", world" + exclam);但在这种情况下,最好通过简单地去掉它们之间的+来连接文字。