// FILE ex_complex2.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_; } double& real () { return real_; } // accessing the imaginary part double imag () const { return imag_; } double& imag() { return imag_; } // adding this complex and x and return the result MyComplex operator+ (const MyComplex& x) const { MyComplex res(real_ + x.real_, imag_ + x.imag_); return res; } // multiplying this complex and x and return the result MyComplex operator* (const MyComplex& x) const { return MyComplex(real_ * x.real_ - imag_ * x.imag_, real_ * x.imag_ + imag_ * x.real_); } // print to output stream void print (ostream& os) const { os << real_ << " + (" << imag_ << " i)"; } }; // class MyComplex inline ostream& operator<< (ostream& os, const MyComplex& x) { x.print (os); return os; } int main () { const MyComplex a(1, 2); // 1 + 2i MyComplex b(2, -3); // 2 - 3i MyComplex c; MyComplex d; cout << "a.real = " << a.real () << endl; b.real () = 5; cout << "a = " << a << endl; cout << "b = " << b << endl; c = a + b; cout << "c = a + b = " << c << endl; d = a * b; cout << "d = a * b = " << d << endl; }