我已经在因特网上经历了一些运营商超载的例子,其中返回类型operator+=
是T&
。由于我们无法链接+=
,例如T a = b = c;
,可以将返回类型声明为void
。使用void
时,一切看起来都正常。有什么情况需要避免吗?运营商的返回类型+ =超载
对于前:
class MyInteger{
private:
int x;
public:
MyInteger(const int& a):x(a){}
void operator+=(const MyInteger& rhs){
x += rhs.x;
}
};
MyInteger a(10);
a += a; //No need to return anything because we can't chain
a = a + (a += a);
“既然我们不能连锁'+ ='”?为什么不? '(((a + = b)+ = c)+ = d)'或'a + =(b + =(c + = d)))''。它像以往一样可以链接。 – AnT
@AnT好的,但我们不需要返回任何东西。因为这些更改是在LHS中进行的,并且可用于下一个操作。所以不需要'T&'作为回报。 –
但是,如果你想链接它,你*有*返回的东西。 – AnT