std::string的operator+,operator<<, operator>>均被定义为非成员运算符重载函数。
那么为什么这几个运算符重载函数要定义为非成员函数呢?
- basic_string的operator>>
template <class _Elem, class _Traits, class _Alloc>
inline basic_istream<_Elem, _Traits>& operator>>(
basic_istream<_Elem, _Traits>& _Istr, basic_string<_Elem, _Traits, _Alloc>& _Str)
输入输出流运算符重载函数第一个参数是*stream引用,如果是类成员函数的第一个参数默认this,即只能是basic_string类型。所以输入输出流运算符重载函数只能写成非成员函数。
- basic_string的operator+
template <class _Elem, class _Traits, class _Alloc>
_NODISCARD inline basic_string<_Elem, _Traits, _Alloc> operator+(const basic_string<_Elem, _Traits, _Alloc>& _Left,
const basic_string<_Elem, _Traits, _Alloc>& _Right)
template <class _Elem, class _Traits, class _Alloc>
_NODISCARD inline basic_string<_Elem, _Traits, _Alloc> operator+(
_In_z_ const _Elem* const _Left, const basic_string<_Elem, _Traits, _Alloc>& _Right)
template <class _Elem, class _Traits, class _Alloc>
_NODISCARD inline basic_string<_Elem, _Traits, _Alloc> operator+(
const _Elem _Left, const basic_string<_Elem, _Traits, _Alloc>& _Right)
template <class _Elem, class _Traits, class _Alloc>
_NODISCARD inline basic_string<_Elem, _Traits, _Alloc> operator+(const basic_string<_Elem, _Traits, _Alloc>& _Left,
_In_z_ const _Elem* const _Right)
template <class _Elem, class _Traits, class _Alloc>
_NODISCARD inline basic_string<_Elem, _Traits, _Alloc> operator+(const basic_string<_Elem, _Traits, _Alloc>& _Left,
const _Elem _Right)
template <class _Elem, class _Traits, class _Alloc>
_NODISCARD inline basic_string<_Elem, _Traits, _Alloc> operator+(const basic_string<_Elem, _Traits, _Alloc>& _Left,
basic_string<_Elem, _Traits, _Alloc>&& _Right)
template <class _Elem, class _Traits, class _Alloc>
_NODISCARD inline basic_string<_Elem, _Traits, _Alloc> operator+(basic_string<_Elem, _Traits, _Alloc>&& _Left,
const basic_string<_Elem, _Traits, _Alloc>& _Right)
template <class _Elem, class _Traits, class _Alloc>
_NODISCARD inline basic_string<_Elem, _Traits, _Alloc> operator+(basic_string<_Elem, _Traits, _Alloc>&& _Left,
basic_string<_Elem, _Traits, _Alloc>&& _Right)
...
从operator+的几种重载声明可以看出,写成非成员函数使得使用更加灵活。string, char*, char类型可以灵活使用operator+。
string&+string&
string&+char*
string&+char
char*+string&
char+string&
string&&+string&&
string&+string&&
string&&+string&
…
如果写成成员函数,则operator+操作的左边数据只能是string。