执行加法时修改第一类对象

First class object is modified when doing a addition

本文关键字:一类 对象 修改 执行      更新时间:2023-10-16

下面的代码给出了正确的加法输出,在执行后更改了第一个对象 bx 值。

class numbers{
public:
    int x;
    numbers(int i1){
        x = i1;
    }
    numbers operator+ (numbers num){
        x = x + num.x;
        return(x);
    }
};
int main(){
    numbers a (2);
    numbers b (3);
    numbers c (5);
    numbers d (7);
    cout << a.x << b.x << c.x << d.x << endl; // returns 2357
    numbers final (100); //this value won't be shown
    final = a+b+c+d; 
    cout << a.x << b.x << c.x << d.x << endl; // returns 5357
    cout << final.x; //returns 17 (2+3+5+7)
    system("pause");
}

问题是,这个加法类究竟是如何工作的?我的意思是,为什么对象 a 中的 x 被修改了?我虽然只有来自最终对象的 x 会被修改。

谢谢:)

对 operator+ 的调用就像任何其他成员函数调用一样。 a + b翻译为a.operator+(b)。因此,在这种情况下x = x + num.x;行实际上是分配给a.x。要实现您想要的,您需要用新值填充新数字,即

numbers operator+ (numbers num) const {
    return numbers(x + num.x)
}

还要注意 const - 当你犯了这个错误时,它会给你一个编译错误。

您编码的运算符 + 实际上正在执行您对运算符 += 的期望

运算符 + 应返回保存计算值的对象编号,而不是修改当前对象。

这里有一些准则

你的operator+会改变this,因为这是你定义它的方式。或者,您可以尝试

numbers operator+( const numbers& num ) {
    numbers ret( this->x ); // constract a local copy
    ret.x += num.x;
    return ret;
}