C++:为什么'operator+='定义字符串,但没有'operator+'?

C++: Why is 'operator+=' defined but not 'operator+' for strings?

本文关键字:operator+ 为什么 C++ 定义 字符串      更新时间:2023-10-16

为什么operator+=被定义为std::stringoperator+没有定义?请看下面我的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;
}

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

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

或在c++ 14中,您将能够使用

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

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

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

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+

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

"abc" + "def"中没有std::string类型的操作数

相关文章: