// FILE ex_complex1.cc #include #include using namespace std; /// a complex number class MyComplex { private: double real_; // real part double imag_; // imaginary part public: // (default) constructor MyComplex (double re=0, double im=0) { real_ = re; imag_ = im; } // accessing the real part double real () const { return real_; } // accessing the imaginary part double imag () const { return imag_; } // setting the real part void setReal (double re) { real_ = re; } // setting the imaginary part void setImag (double im) { imag_ = im; } // print to screen void print () const { cout << real_ << " + (" << imag_ << " i)" << endl; } }; // class MyComplex void addComplex (const MyComplex x, const MyComplex y, MyComplex& z) { z.setReal (x.real() + y.real ()); z.setImag (x.imag() + y.imag ()); } void multComplex (MyComplex x, MyComplex y, MyComplex& z) { z.setReal (x.real() * y.real() - x.imag() * y.imag()); z.setImag (x.real() * y.imag() + x.imag() * y.real()); } int main () { MyComplex a(1, 2); // 1 + 2i MyComplex b(2, -3); // 2 - 3i MyComplex c; MyComplex d; cout << "a = "; a.print (); cout << "b = "; b.print (); addComplex (a, b, c); cout << "c = a + b = "; c.print (); multComplex (a, b, d); cout << "d = a * b = "; d.print (); }