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

标签 c++ string c++11 literals

<分区>

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
}

最佳答案

[expr.add]p1 :

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

+- 是左关联的,这意味着最后两个定义实际上是这样的:

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

现在错误很明显:"hello"+ ", " 首先被求值,但是因为 const char[] 没有加法运算符,你得到一个编译器错误。如果运算符是右结合的,s7 将有效,而 s6 则无效。

关于c++ - 在 C++ 中添加字符串和文字的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48113004/

相关文章:

c++ - 如何取消定义_MSC_VER?

c++ - 对象映射的 vector

c++ - 如何告诉编译器不要内联类定义中定义的方法,under/ob1 优化?

c++ - typedef 模板类实例

string - Prolog获取字符串的头部和尾部

c++ - static_pointer_cast 通过继承和模板

c# - 在上标中添加字符串 3

javascript - 如何使用正则表达式用 Javascript 替换字符串中特定单词以外的所有内容

c++ - 不同大小数组的迭代器

c++ - 为什么非静态数据成员不能是 constexpr?