Reputation: 55
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 ??
Upvotes: 0
Views: 55
Reputation: 60238
Your operator+
is modifying the left hand operand. Instead, you should create a new object and return that:
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;
}
The same logic applies to operator-
.
Upvotes: 2