mardi 21 juillet 2020

Object getting modified in Operator overloading

I've written this code to perform operations on complex numbers using 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;
}

OUTPUT:

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

As you can see after - operation the object gets modified which results in wrong answer in the next operation(in this case +). Can anyone help me out as to how I can fix this thing ??

Aucun commentaire:

Enregistrer un commentaire