我是C++的新手,我指的是Accelerated C++。虽然尝试的行使问题,其中一个说:在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'对象)使用'+'。 – birryree
下面的答案解释了代码不起作用的原因;我添加了另一种修复代码的方式。您可以通过添加圆括号来改变操作顺序,以确保所有连接都调用了std :: string :: operator +'。 'const std :: string message =“Hello”+(“,world”+ exclam);'但是在这种情况下,最好通过简单地除去它们之间的'+'来连接文字。 – Praetorian