从std::string类理解非成员运算符重载

博客讨论了C++中std::string的operator+、operator<<和operator>>为何定义为非成员函数。这样做允许更灵活的操作,如不同类型的字符串和字符可以方便地进行拼接和输入输出。非成员函数形式使得输入输出流操作符能接受不同类型参数,而成员函数则限制了其灵活性。
摘要由CSDN通过智能技术生成

std::string的operator+,operator<<, operator>>均被定义为非成员运算符重载函数。
那么为什么这几个运算符重载函数要定义为非成员函数呢?

  1. 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类型。所以输入输出流运算符重载函数只能写成非成员函数。

  1. 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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值