C++:为什么'operator+='定义字符串,但没有'operator+'?
C++: Why is 'operator+=' defined but not 'operator+' for strings?
为什么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;
}
需要将其中一个原始字符串显式地转换为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
类型的操作数
相关文章:
- 为什么 std::optional::operator=(U&&) 要求你是非标量类型?
- 为什么 operator() 处的指针成员不起作用?
- 为什么 string_view::operator== 按值接受参数
- 为什么当我没有变量或其他任何命名的东西时"no match for 'operator==' "错误?
- 为什么当我使用 std::string::operator[] 时自动变量不会成为引用?
- 为什么地图需要实现'operator<'以及如何比较对象?
- 从 std::ostream 重载 << 运算符时,为什么编译器会给出"too many parameters for this operator function"错误?
- 为什么当"::"的行为不像运算符时被称为'scope resolution operator'?
- 为什么许多标准库类型在 C++20 中删除 operator!=?
- 为什么我收到以下错误:"no match for 'operator=='"?(带模板的嵌套类)
- 为什么 std::uniform_int_distribution<IntType>::operator() 不是 const?
- 为什么我可以在临时 std::ofstream 对象上使用"operator<<"?
- 为什么C++不为枚举类型提供默认"operator>>"函数?
- 为什么 mkdir() 后跟 ofstream::operator<< 失败并被拒绝权限?
- 为什么调用 cout.operator<<(const char*) 打印地址而不是字符串? 如何创建一个函数本地静态"HashSet<char>"并初始化它一次?
- 如果类对象需要在 C++ 中转换为 int,为什么会调用 "operator bool()"?
- 在 [over.ass]/2 的例子中,为什么 *bptr = dobj2;调用 D::operator=(const B&)?
- 为什么需要"std::function::operator=(F &&)"来制作临时的"std::function"?
- operator[] -为什么我不应该使用它
- std::unordered_map::operator[]-为什么有两个签名