问题描述
class Currency
{
public:
explicit Currency(unsigned int value);
// method form of operator+=
Currency &operator +=(const Currency &other); // understood!
...
};
以下代码显示了使用免费版本的运算符的等效API:
The following code shows an equivalent API using a free function version of the operator:
class Currency
{
public:
explicit Currency(unsigned int value);
...
};
// free function form of operator+=
Currency &operator +=(Currency &lhs, const Currency &rhs); // ???
Question1 为什么自由函数应该返回Currency&
而不是Currency
?这是一个好习惯吗?
Question1> Why should the free function return Currency&
instead of Currency
?Is this a good practice?
Question2 在实现中,应该使用哪个变量返回lhs
或rhs
?
Question2> In the implementation, which variable should be used to return, lhs
or rhs
?
推荐答案
operator+=
的标准行为是将lhs增加rhs并返回对lhs的引用.
The standard behavior of operator+=
is to increment the lhs by the rhs and return a reference to the lhs.
在成员函数中,lhs是调用对象,因此,它应该返回对自身的引用.您似乎期望自由函数的行为不同于成员函数.为什么?
In the member function, the lhs is the calling object, and accordingly, it should return a reference to itself. You seem to expect the free function to behave differently than the member function. Why?
这篇关于免费运营商与会员运营商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!