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 >为什么自由函数应该返回Currency&
而不是Currency
?
这是一个好习惯吗?
问题2 >在实现中,应使用哪个变量返回lhs
或rhs
?
答案 0 :(得分:5)
operator+=
的标准行为是通过rhs递增lhs并返回对lhs的引用。
在成员函数中,lhs是调用对象,因此它应该返回对自身的引用。您似乎期望自由函数的行为与成员函数不同。为什么呢?
答案 1 :(得分:2)
问题1:“自由函数”无法访问Currency类的私有成员变量。如果需要使用这些变量来执行+=
操作,那么您应该使操作符成为类的成员,或者使非成员操作符成为类的朋友(请参阅下面的示例)。除此之外,它们非常相似。
问题2:返回lhs
。这允许您将呼叫链接在一起,例如a += b += c
。
class Currency
{
friend Currency& operator+=(Currency &lhs, const Currency &rhs);
};
Currency& operator+=(Currency &lhs, const Currency &rhs)
{
}
与
相同class Currency
{
public:
friend Currency& operator+=(Currency &lhs, const Currency &rhs)
{
}
};
答案 2 :(得分:0)
关于第一个问题。实际上你可以按值返回对象。但是你应该总是更喜欢通过引用(或指针)返回值来返回。因为按值返回涉及复制ctor调用。它会降低性能。在上面的情况下,你肯定可以返回参考,所以这样做:)
请看Scott Meyers的书“Effective C ++”。第23项:当您必须返回一个物体时,不要尝试返回参考。有关详细信息。
答案 3 :(得分:0)
这对于返回lhs位的运算符来说是好的,也就是说好 - 即给编译器提示它不需要创建新对象。但是像+, - ,*等运算符不会像返回的值
那样真实