【问题标题】:Problems with adding string and literals in C++ [duplicate]在 C++ 中添加字符串和文字的问题 [重复]
【发布时间】:2018-06-15 05:32:08
【问题描述】:

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
}

【问题讨论】:

    标签: c++ string c++11 literals


    【解决方案1】:

    [expr.add]p1:

    加法运算符 + 和 - 从左到右分组。 [...]

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

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

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

    【讨论】:

      【解决方案2】:

      这是由于 + 运算符具有从左到右的关联性。

      在这里找到更好的描述: Concatenate two string literals

      【讨论】:

        【解决方案3】:

        "hello"", " 等“字符串文字”的概念与“std::string 对象”的概念有所不同。

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

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

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

        另一方面,以下声明:

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

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-07-27
            • 1970-01-01
            • 2021-06-20
            • 2010-12-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多