1

为了更加熟悉 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+=vu=1-2i。为什么会这样?

4

2 回答 2

2

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

在类定义中声明运算符,例如

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

并通过以下方式定义它

Complex & Complex::operator+=(const Complex& u) {
    _real += u._real;
    _imag += u._imag;

    return *this;
}

The operator can be defined as a non-class friend function. For example

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;
}
于 2019-10-22T15:15:13.363 回答
1

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

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

有几个解决方案:

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;
}
于 2019-10-22T15:14:27.860 回答