When I use this->
operator it saves the value of complex number having higher magnitude of real value in compare function, but it also overrides the value of real variable. I am unable to assess the value of c2.real
.
#include <iostream>
using namespace std;
class Complex
{
int real,img;
public:
void get()
{
cin>>real>>img;
}
void display()
{
cout<<real<<"+"<<img<<"i"<<endl;
}
Complex &compare(Complex&);
Complex &add(Complex&);
};
int main()
{
Complex c1,c2,c3;
c1.get();
c2.get();
c3=c1.compare(c2);
c3.display();
c3=c1.add(c2);
c3.display();
return 0;
}
For example for inputs 2+4i
and 7+9i
this function compare check for real value having high magnitude and saves the value 7 and 9 in real
and img
variables.
Complex& Complex::compare(Complex &a)
{
if(real>a.real)
{
this->real=real;
this->img=img;
}
else
{
this->real=a.real;
this->img=a.img;
}
return *this;
}
But now when I use add function it gives a sum of 14+18i which is 7+8i + 7+8i
why the value of object c2.real
and c2.img
have been overwritten and what can i do to have a sum of 2+4i and 7+8i.
Also this is a hacker rank question so the main function and class block are locked and cannot be edited I can only edit the compare and add function definitions.
Complex& Complex::add(Complex &b)
{
this->real=real+b.real;
this->img=img+b.img;
return *this;
}