自由运营商与会员运营商

q09*_*987 4 c++ operator-overloading

class Currency
{
public:
    explicit Currency(unsigned int value);
    // method form of operator+=
    Currency &operator +=(const Currency &other); // understood!
    ...
};
Run Code Online (Sandbox Code Playgroud)

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

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

// free function form of operator+=
Currency &operator +=(Currency &lhs, const Currency &rhs); // ???
Run Code Online (Sandbox Code Playgroud)

问题1 >为什么自由函数返回Currency&而不是Currency?这是一个好习惯吗?

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

Ben*_*ley 5

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

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