I am having trouble figuring out why my complex number class isn't adding correctly or working exactly how I want it to. When I add two complex numbers together I get something really weird that isn't supposed to be. I keep trying to figure out what's wrong, but can't quite figure it out. I need to keep the structure because I am going to use it for another purpose.
#include <iostream>
#include <cmath>
using namespace std;
class ComplexNumber{
private:
double real, imag;
public:
ComplexNumber(double i,double j){
real = i;
imag = j;}
ComplexNumber add(ComplexNumber c){
real += c.real;
imag += c.imag;
}
ComplexNumber squared(){
real = (pow(real,2) - pow(imag,2));
imag = 2*real*imag;
}
double abs() {
return sqrt(real*real + imag*imag);
}
void print(){
char sign = (imag<0) ? '-' : '+';
cout<<real<<" "<<sign<<" "<<(imag>0 ? imag : -imag)<<'i'<<endl;
}
};
int main() {
ComplexNumber c1(3,4), c2(1,1);
ComplexNumber c3=c1.add(c2);
c3.print();
return 0;
}
Your
add
member function promises to return aComplexNumber
but it doesn't. You then attempt to use the return value, invoking undefined behaviour.squared
is similarly broken.You need to figure out whether you want
add
to implement the behaviour of operator+=
or+
. In the first case, you'd need to return a reference to the object being modified:In the second case, do not modify the object but create a new one and return it:
Note that in this case it may make sense to use a non-member function instead.
I suggest looking at
std::complex
for an example of a good implementation.