TL;DR operator+=
是一个类成员函数class string
, while operator+
是一个模板函数。
标准班template<typename CharT> basic_string<CharT>
具有重载功能basic_string& operator+=(CharT)
,字符串只是basic_string<char>
.
由于适合较低类型的值可以自动转换为该类型,因此在表达式中s += 2
, 2 是not像...一样对待int
, but char
反而。它有exactly效果与s += '\x02'
。附加一个带有 ASCII 代码 2 (STX) 的字符,not字符“2”(ASCII 值为 50 或 0x32)。
但是,字符串没有像这样的重载成员函数string operator+(int)
, s + 2
不是有效的表达式,因此会在编译期间引发错误。 (更多内容见下文)
您可以通过以下方式在字符串中使用运算符+函数:
s = s + char(2); // or (char)2
s = s + std::string(2);
s = s + std::to_string(2); // C++11 and above only
对于那些担心为什么 2 不会自动转换为的人char
with operator+
,
template <typename CharT>
basic_string<CharT>
operator+(const basic_string<CharT>& lhs, CharT rhs);
The above is the prototype[note] for the plus operator in s + 2
, and because it's a template function, it is requiring an implementation of both operator+<char>
and operator+<int>
, which is conflicting. For details, see Why isn't automatic downcasting applied to template functions? https://stackoverflow.com/questions/45506372
同时,原型operator+=
is:
template <typename CharT>
class basic_string{
basic_string&
operator+=(CharT _c);
};
你看,这里没有模板(它是一个类成员函数),所以编译器推断出 CharT 类型是char
来自类实现,以及int(2)
会自动转换为char(2)
.
Note: Unnecessary code is stripped when copying from C++ standard include source. That includes typename 2 and 3 (Traits and Allocator) for template class "basic_string", and unnecessary underscores, in order to improve readability.