免费运营商与会员运营商

2024-01-05

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> 为什么free函数要返回Currency&代替Currency? 这是一个好的做法吗?

问题2> 实现中,应该用哪个变量来返回,lhs or rhs?


标准行为operator+=是将 lhs 增加 rhs 并返回对 lhs 的引用。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

免费运营商与会员运营商 的相关文章

随机推荐