【问题标题】:Overloading compound-assignment-operator in C++ does not change variable在 C++ 中重载复合赋值运算符不会改变变量
【发布时间】:2020-02-18 18:48:34
【问题描述】:

为了更加熟悉 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。为什么会这样?

【问题讨论】:

标签: c++ class operator-overloading compound-assignment


【解决方案1】:

您的复合赋值运算符创建一个新对象 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;
}

【讨论】:

  • 这很有帮助。为什么要通过引用返回结果?
  • @Samuel 因为这是operator+= 应该做的。另请参阅stackoverflow.com/questions/4421706/…
  • @Samuel 在与 C 相对的 C++ 中,赋值运算符返回左值引用。例如,在 C++ 中,您可以编写 int x = 1;整数 y = 10; ( x += y ) *= 10;
【解决方案2】:

首先,类似赋值的操作符应该返回对赋值的引用。

其次,你的代码应该改变当前对象的值。

有几种解决方案:

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;
}

【讨论】:

  • 哪种解决方案更好?
  • 从编译器的角度来看没有区别(“好像”规则)。所以只是个人喜好。
猜你喜欢
  • 2020-03-23
  • 1970-01-01
  • 2021-05-11
  • 2019-11-17
  • 2020-04-17
  • 2020-10-20
  • 2012-08-17
  • 1970-01-01
  • 2013-03-30
相关资源
最近更新 更多