C++中重载复合赋值运算符不会更改变量

Overloading compound-assignment-operator in C++ does not change variable

本文关键字:改变 变量 赋值运算符 重载 复合 C++      更新时间:2023-10-16

为了更加熟悉C++,我正在实现一个处理复数的类。

class Complex {
private:
double _real;
double _imag;
public:
Complex();
Complex(double real, double imag);
Complex(const Complex& z);
Complex operator+(const Complex& u) const;
Complex operator+=(const Complex& u);
};

我已经超载了+运算符,它按预期工作:

Complex Complex::operator+(const Complex& u) const {
Complex z(_real + u._real, _imag + u._imag);
return z;
}
u=1-2i
v=2-1i
u+v=3-3i

此外,我还想过载+=

Complex Complex::operator+=(const Complex& u) {
Complex z(_real + u._real, _imag + u._imag);
return z;
}

然而,这并没有如预期的那样工作,并且u+=v的结果是u=1-2i。为什么会这样?

您的复合赋值运算符创建一个新对象z,而不是更改原始对象。

在类定义中声明操作符,如

Complex & operator+=(const Complex& u);

并以以下方式定义

Complex & Complex::operator+=(const Complex& u) {
_real += u._real;
_imag += u._imag;
return *this;
}

运算符可以定义为非类友元函数。例如

class Complex {
private:
double _real;
double _imag;
public:
Complex();
Complex(double real, double imag);
Complex(const Complex& z);
Complex operator+(const Complex& u) const;
friend Complex & operator+=(Complex &v, const Complex& u);
};
Complex & operator+=(Complex &v, const Complex& u)
{
v._real += u._real;
v._imag += u._imag;
return v;
}

首先,类赋值运算符应该返回对赋值的引用。

其次,您的代码应该更改当前对象的值。

有两种解决方案:

Complex& Complex::operator+=(const Complex& u) {
*this = Complex(_real + u._real, _imag + u._imag);
return *this;
}

Complex& Complex::operator+=(const Complex& u) {
_real += u._real;
_imag += u._imag;
return *this;
}