c++ - Problems with personally constructed complex number class -
i having trouble figuring out why complex number class isn't adding correctly or working how want to. when add 2 complex numbers weird isn't supposed be. keep trying figure out what's wrong, can't quite figure out. need keep structure because going use 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 return complexnumber
doesn't. attempt use return value, invoking undefined behaviour. squared
broken.
you need figure out whether want add
implement behaviour of operator +=
or +
. in first case, you'd need return reference object being modified:
complexnumber& add(complexnumber c) {// ^ real += c.real; imag += c.imag; return *this; }
in second case, not modify object create new 1 , return it:
complexnumber add(complexnumber c) { return complex(real + c.real, imag + c.imag); }
note in case may make sense use non-member function instead.
i suggest looking @ std::complex
example of implementation.
Comments
Post a Comment