home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_13_04 / saks / z1.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1995-02-02  |  1.5 KB  |  73 lines

  1. Listing 3 - A rudimentary class a rudimentary class for
  2. complex numbers which recomputes the polar form on demand
  3.  
  4. // z1.cpp
  5.  
  6. #include <iostream.h>
  7. #include <iomanip.h>
  8. #include <math.h>
  9.  
  10. class complex
  11.     {
  12. public:
  13.     complex(double r, double i);
  14.     double real() const;
  15.     double imag() const;
  16.     double rho() const;
  17.     double theta() const;
  18. private:
  19.     double re, im;
  20.     };
  21.  
  22. inline complex::complex(double r, double i)
  23.     : re(r), im(i)
  24.     {
  25.     }
  26.  
  27. inline double complex::real() const
  28.     {
  29.     return re;
  30.     }
  31.  
  32. inline double complex::imag() const
  33.     {
  34.     return im;
  35.     }
  36.  
  37. inline double complex::rho() const
  38.     {
  39.     return sqrt(re * re + im * im);
  40.     }
  41.  
  42. inline double complex::theta() const
  43.     {
  44.     return atan2(im, re);
  45.     }
  46.  
  47. complex operator+(const complex &z1, const complex &z2)
  48.     {
  49.     return complex
  50.         (z1.real() + z2.real(), z1.imag() + z2.imag());
  51.     }
  52.  
  53.  
  54. int main()
  55.     {
  56.     complex z1(3, 4);
  57.     cout << '(' << z1.real() << ',' << z1.imag() << ')'
  58.         << endl;
  59.     cout << '(' << z1.rho() << ',' << z1.theta() << ')'
  60.         << endl;
  61.     complex z2(1, 1);
  62.     cout << '(' << z2.real() << ',' << z2.imag() << ')'
  63.         << endl;
  64.     cout << '(' << z2.rho() << ',' << z2.theta() << ')'
  65.         << endl;
  66.     z1 = z1 + z2;
  67.     cout << '(' << z1.real() << ',' << z1.imag() << ')'
  68.         << endl;
  69.     cout << '(' << z1.rho() << ',' << z1.theta() << ')'
  70.         << endl;
  71.     return 0;
  72.     }
  73.