// my_complex.cc a partial, non template, complex class // demonstrate some operator+ must be non-member functions // operator<< and operator >> must be non-member functions #include using namespace std; class my_complex { public: my_complex() { re=0.0; im=0.0; } // three typical constructors my_complex(double x) { re=x; im=0.0; } my_complex(double x, double y):re(x),im(y) {} // { re=x; im=y; } my_complex operator+(my_complex & z) // for c = a + b { return my_complex(re+z.real(), im+z.imag()); } my_complex operator+(double x) // for c = a + 3.0 { return my_complex(re+x, im); } // many other operators would typically be defined double real(void) { return re; } double imag(void) { return im; } friend ostream &operator<< (ostream &stream, my_complex &z); private: double re; // the data values for this class double im; }; // non member functions my_complex operator+(double x, my_complex z) // for c = 3.0 + a { return z+x; } ostream &operator<< (ostream &stream, my_complex &z) { stream << "(" << z.real() << "," << z.imag() << ")"; return stream; } int main() { my_complex a(2.0, 3.0); cout << a << " =a\n"; my_complex b(4.0); cout << b << " =b\n"; my_complex c = my_complex(5.0, 6.0); cout << c << " =c\n"; my_complex d; cout << d << " =d\n"; c = a + c; cout << c << " c=a+c\n"; c = 3.0 + a; // not legal without non member function operator+ cout << c << " c=3.0+a\n"; c = a + 3.0; // not legal without second operator+ on double cout << c << " c=a+3.0\n"; c = a + 3; // not legal without second operator+ on double // uses standard "C" C++ conversion int -> float -> double cout << c << " c=a+3\n"; d = c.imag(); cout << d << " d=c.imag()\n"; return 0; } // Output from running my_complex.cc // (2,3) =a // (4,0) =b // (5,6) =c // (0,0) =d // (7,9) c=a+c // (5,3) c=3.0+a // (5,3) c=a+3.0 // (5,3) c=a+3 // (3,0) d=c.imag()