C++ 重载+;=操作人员
重载+=运算符时,为什么必须通过引用返回。 例如,下面的代码也执行相同的操作C++ 重载+;=操作人员,c++,C++,重载+=运算符时,为什么必须通过引用返回。 例如,下面的代码也执行相同的操作 class Integer { int i; public: Integer::Integer(int i):i(i){} void operator+=(const Integer& arg) { i = i + arg.i; } }; //main.cpp int _tmain(int argc, _TCHAR* argv[]) { Integer
class Integer
{
int i;
public:
Integer::Integer(int i):i(i){}
void operator+=(const Integer& arg)
{
i = i + arg.i;
}
};
//main.cpp
int _tmain(int argc, _TCHAR* argv[])
{
Integer a(10),b(20);
b += a;
}
大多数书籍建议,对于上述运算符,重载函数应通过引用返回,即如下所示:
Integer& operator+=(const Integer&)
{
i = i + arg.i;
return *this;
}
如果我们通过引用返回,那么当执行以下语句时,返回对象引用会发生什么情况:
b+=a 因此T&x=(y+=z)代码>与基本类型一致
如果我们通过引用返回,那么返回对象会发生什么
执行以下语句时引用:
b+=a代码>
没什么。语句被执行,引用未使用,b
继续使用它的生命周期
通过引用返回允许的有趣功能是链接调用:如果不通过引用返回,则不能执行(b++=b)+=a
。
这看起来是这样的:(void)+=const Integer&
,因为b+=b
属于void
类型,因为运算符+=
返回void
可能重复的(a+=b)+=c
会这样做。void运算符+=(const Integer&arg)是否也会按预期工作。否,因为您无法初始化T&x代码>带有类型为void
的表达式。