加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 自由操作符与会员操作符

发布时间:2020-12-16 09:39:12 所属栏目:百科 来源:网络整理
导读:class Currency{public: explicit Currency(unsigned int value); // method form of operator+= Currency operator +=(const Currency other); // understood! ...}; 以下代码显示了使用运算符的自由函数版本的等效API: class Currency{public: explicit C
class Currency
{
public:
    explicit Currency(unsigned int value);
    // method form of operator+=
    Currency &operator +=(const Currency &other); // understood!
    ...
};

以下代码显示了使用运算符的自由函数版本的等效API:

class Currency
{
public:
    explicit Currency(unsigned int value);
    ...
};

// free function form of operator+=
Currency &operator +=(Currency &lhs,const Currency &rhs); // ???

问题1>为什么免费功能会返回货币&而不是货币?
这是一个好习惯吗?

问题2>在实现中,应该使用哪个变量返回,lhs还是rhs?

解决方法

operator =的标准行为是通过rhs递增lhs并返回对lhs的引用.

在成员函数中,lhs是调用对象,因此,它应该返回对自身的引用.您似乎期望自由函数的行为与成员函数不同.为什么?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读