This question already has answers here:
Concatenate two string literals
(6个答案)
2年前关闭。
在
现在,错误显而易见:首先对
(6个答案)
2年前关闭。
在
s6
和s7
的定义中,如何在s6
中为每个+加上一个字符串,为什么在s7
中还不是这样?#include <string>
using std::string;
int main()
{
string s1 = "hello", s2 = "world";
string s3 = s1 + ", " + s2 + '\n';
string s4 = s1 + ", "; // ok: adding a string and a literal
string s5 = "hello" + ", "; // error: no string operand
string s6 = s1 + ", " + "world"; // ok: each + has a string operand
string s7 = "hello" + ", " + s2; // error: can't add string literal
}
最佳答案
[expr.add]p1:
+
和-
保持关联,这意味着实际上最后两个定义如下所示:
string s6 = (s1 + ", ") + "world";
string s7 = ("hello" + ", ") + s2;
现在,错误显而易见:首先对
"hello" + ", "
求值,但是由于没有const char[]
的加法运算符,因此会出现编译器错误。如果运算符正确关联,则s7
将有效,而s6
将无效。08-07 17:38