[   ^ to index...   |   <-- previous   ]

Putting it together: complex numbers

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; }

Download sample code...


Last modified: Thu Jul 27 13:58:40 PDT 2000