添加字符串和文字,顺序如何影响是否可以正确添加字符串

Adding strings and literals, how does the order affect if you can add the strings without error

本文关键字:字符串 添加 是否 影响 文字 顺序 何影响      更新时间:2023-10-16

请考虑以下字符串定义:

string s1 = "hello", s2 = "world";
string s6 = s1 + ", " + "world";
string s7 = "hello" + ", " + s2;

C++ Primer 5e 的书指出,第三行将导致编译器给出错误,因为您无法添加字符串文字。编译器给出的实际错误是

error: invalid operands of types 'const char [6]'
and 'const char [3]' to binary 'operator+'

但是第二个字符串s6不是和s7做完全相同的事情吗?有什么区别?

由于加法从左到右关联,因此s6被解析为(s1 + ", ") + "world"。 这会给const char *增加一个string,导致另一个string。 然后我们向该string添加另一个const char *,从而产生存储在s6中的第三个string

s7被解析为("hello" + ", ") + s2,它试图将一个const char *添加到另一个const char *,这是你不能做的。 您可以将其重写为 "hello" + (", " + s2)然后进行编译。