【问题标题】:C++: Why is 'operator+=' defined but not 'operator+' for strings? [duplicate]C ++:为什么为字符串定义了'operator + ='而不是'operator +'? [复制]
【发布时间】:2014-08-30 20:27:49
【问题描述】:

为什么为std::string 定义了operator+= 而没有定义operator+?请参阅下面的 MWE (http://ideone.com/OWQsJk)。

#include <iostream>
#include <string>
using namespace std;

int main() {  
    string first;
    first = "Day";
    first += "number";
    cout << "\nfirst = " << first << endl;

    string second;
    //second = "abc" + "def";       // This won't compile
    cout << "\nsecond = " << second << endl;
    return 0;
}

【问题讨论】:

  • 您希望:"abc"-&gt;operator+("def") 工作?
  • @crashmstr 好吧,我明白他们为什么会这样做。它会在许多其他语言中(也就是说,字符串文字是类类型)。

标签: c++ string c++11 operators


【解决方案1】:

您需要将原始字符串文字之一显式转换为std::string。你可以像其他人已经提到的那样做:

second = std::string("abc") + "def";

或使用 C++14,您将能够使用

using namespace std::literals;
second = "abc"s + "def";
// note       ^

【讨论】:

    【解决方案2】:

    那些不是std::strings,他们是const char *。试试这个:

     second = std::string("abc") + "def";
    

    【讨论】:

    • 技术上他们不是const char*,他们是const char[4]
    • @MooingDuck 也非技术性的 :-)
    • @MooingDuck 从技术上讲,他们是const char (&amp;)[4]
    • @0x499602D2:我差点就打出来了,但我认为文字不是引用,它们是值。刚刚测试,它确实绑定到一个可变引用,所以我猜你是对的,它们是引用:coliru.stacked-crooked.com/a/b60f5bc56c82e568。实际上,也许它们只是左值?我不知道。
    • @0x499602D2 来自您的链接:“字符串文字的类型已更改......为 const char 数组。” "如果e 是一个左值,decltype(e)T&amp;,其中Te 的类型;"很明显 e 的类型是 T 而不是参考。 decltype("literal") 是一个引用,但 "literal" 只是一个左值。
    【解决方案3】:

    C++:为什么为字符串定义了 'operator+=' 而不是 'operator+'?

    是的。它要求至少有一个操作数是std::string

    int main() 
    {
      std::string foo("foo");
      std::string bar("bar");
      std::string foobar = foo + bar;
      std::cout << foobar << std::endl;
    }
    

    您的问题是您尝试添加字符串文字"abc""def"。这些类型为const char[4]。这些类型没有operator+

    【讨论】:

      【解决方案4】:

      + 仅在至少一个操作数是std::string 类型时才能连接两个字符串。

      "abc" + "def" 中,没有一个操作数是std::string 类型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-20
        • 1970-01-01
        • 2018-07-11
        • 1970-01-01
        • 2018-08-03
        • 2020-08-28
        • 2018-07-30
        相关资源
        最近更新 更多