/* Code of Figure 10.14, page 445 from Kenneth C. Louden, Programming Languages Principles and Practice 2nd Edition Copyright (C) Brooks-Cole/ITP, 2003 Test code from pages 445-446 also added */ #include using std::cout; using std::endl; class Complex { public: Complex(double r = 0, double i = 0) : re(r), im(i) { } double realpart() { return re; } double imaginarypart() { return im; } Complex operator-() // unary minus { return Complex( -re, -im); } Complex operator+( Complex y) { return Complex( re + y.realpart(), im + y.imaginarypart()); } Complex operator-(Complex y) // subtraction { return Complex( re - y.realpart(), im - y.imaginarypart()); } Complex operator*(Complex y) { return Complex(re * y.realpart() - im * y.imaginarypart(), im * y.realpart() + re * y.imaginarypart()); } private: double re,im; }; int main() { Complex z(1,2); Complex w(-1,1); Complex x = z + w; Complex i(0,1); // i constructed as (0,1) Complex y; // y constructed as default (0,0) Complex xx(1); // xx constructed as (1,0) cout << z.realpart() << " + i " << z.imaginarypart() << endl; cout << w.realpart() << " + i " << w.imaginarypart() << endl; cout << x.realpart() << " + i " << x.imaginarypart() << endl; cout << i.realpart() << " + i " << i.imaginarypart() << endl; cout << y.realpart() << " + i " << y.imaginarypart() << endl; cout << xx.realpart() << " + i " << xx.imaginarypart() << endl; return 0; }