#include #include class Complex { private: double real, imag; public: // Note use of default argument in 2nd constructor Complex() : real(0), imag(0) {} Complex(double r, double i = 0) : real(r), imag(i) {} double getReal() { return real; } double getImag() { return imag; } // It is natural to define addition on complex numbers Complex operator+(const Complex& other) { return Complex(real + other.real, imag + other.imag); } // When we want to add a double to a Complex, we use // a friend function because double is a primitive friend Complex operator+(double left, const Complex& right); // Define the inverse operation in terms of the above Complex operator+(double other) { return other + *this; } // Define a default conversion for convenience // (a bit dangerous, may lead to ambiguities) operator double() { assert(imag == 0); return real; } // What's this? friend ostream& operator<<(ostream& out, const Complex& c); }; Complex operator+(double left, const Complex& right) { // May access right's privates due to friend status return Complex(left + right.real, right.imag); } // What's this? ostream& operator<<(ostream& out, const Complex& c) { out << '(' << c.real << ',' << c.imag << ')'; return out; } int main() { Complex c(2.0,1.0); cout << c << endl; // Invokes operator<<(ostream&, const Complex&) Complex d = c + 2.0; // invokes Complex::operator+(const Complex&) cout << d << endl; Complex cprime(3.0); // invokes second constructor double e(cprime); // invokes operator double() double f = 7.0 + cprime; // invokes operator+, then operator double cout << e << endl; cout << f << endl; return 0; }