C ++:为什么'运算符+ ='定义但不是'运营商+'对于字符串?

时间:2014-07-09 17:19:58

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

如何为operator+=定义std::string,但未定义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;
}

4 个答案:

答案 0 :(得分:9)

您需要明确地将其中一个原始字符串文字转换为std::string。你可以像其他已经提到过的那样做:

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

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

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

答案 1 :(得分:6)

那些不是std::string,它们是const char *。试试这个:

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

答案 2 :(得分:4)

  

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+

答案 3 :(得分:0)

仅当至少一个操作数的类型为+时,

std::string才能连接两个字符串。

"abc" + "def"中,操作数均不属于std::string类型。