对象在运算符重载中被修改

Object getting modified in Operator overloading

我编写了这段代码来使用运算符重载对复数执行运算:

#include<iostream>

using namespace std;

class Complex{
    private:
        float real;
        float img;
    public:
        Complex():real(0),img(0){

        }
        Complex(float real,float img):real(real),img(img){

        }
        Complex operator+(const Complex &other){
            real=this->real+other.real;
            img=this->img+other.img;
            return *this;

        }
       
        Complex operator-(const Complex &diff){
          
            real=this->real-diff.real;
            img=this->img-diff.img;
            return *this;


        }
        void print(){
            cout<<real<<" + i"<<img<<endl;
        }
};

int main(){
    Complex c1(1,7),c2(2,2);
    c1.print();
    c2.print();

    
   
    Complex c3;
    c3=c1-c2;
    c3.print();

    Complex c4;
    c4=c1+c2;
    c4.print();

   
    

    return 0;
}

输出:

1 + i7
2 + i2
-1 + i5
1 + i7

如您所见,在 - 操作之后,对象被修改,导致下一个操作中的错误答案(在本例中为 +)。 谁能帮我解决这个问题??

您的 operator+ 正在修改左侧操作数。相反,您应该创建一个新对象并且 return 那:

Complex operator+(const Complex &other) const {
                                      //^^^^^ make sure not to change *this
  Complex ret; // create a separate object
  ret.real = this->real+other.real;
  ret.img = this->img+other.img;
  return ret; 
}

同样的逻辑适用于operator-