在 C++ 中添加字符串和文字的问题

Problems with adding string and literals in C++

s6s7的定义中,为什么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
}

这是因为 + 运算符具有从左到右的结合性。

在此处找到对此的更好描述: Concatenate two string literals

[expr.add]p1:

The additive operators + and - group left-to-right. [...]

+- 是左结合的,这意味着实际上,最后两个定义看起来像这样:

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

现在错误很明显:首先计算 "hello" + ", ",但是因为 const char[] 没有加法运算符,所以会出现编译错误。如果运算符是右结合的,则 s7 有效,而 s6 无效。

无需添加字符串文字 "hello" ", " 将由预处理器粘贴到 "hello, "

"string literal" 的概念(例如 "hello"", ")与“std::string 对象”之间存在差异。

字符串文字只是 char[] 并且将两个字符串文字相加并没有您认为的效果。您只是添加了两个指针,这对您的情况没有任何意义。

另一方面,operator+() 方法是在操作数 std::stringchar* 上定义的,因此它 returns 是一个 std::string 对象。这是您缺少的另一个概念发挥作用的时候:运算符关联性。在下面一行的情况下:

string s6 = s1 + ", " + "world";
  1. s1 + ", "returns一个std::string
  2. 返回的对象连接到 "world",还返回一个 std::string 对象。这按预期工作

另一方面,以下声明:

string s7 = "hello" + ", " + s2;

没有按预期工作,因为正在评估的表达式的第一部分是 "hello" + ", ",这是尝试添加 2 个字符串文字。