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 / z3.cpp < prev   
Encoding:
C/C++ Source or Header  |  1995-02-02  |  1.1 KB  |  54 lines

  1. Listing 5 - A rudimentary class for complex numbers using a
  2. mutable member to implement "lazy" evaluation and caching
  3. for polar form
  4.  
  5. // z3.cpp
  6.  
  7. #include <iostream.h>
  8. #include <iomanip.h>
  9. #include <math.h>
  10.  
  11. class complex
  12.     {
  13. public:
  14.     complex(double r, double i);
  15.     complex(const complex &z);
  16.     complex &operator=(const complex &z);
  17.     ~complex();
  18.     double real() const;
  19.     double imag() const;
  20.     double rho() const;
  21.     double theta() const;
  22. private:
  23.     double re, im;
  24.     struct polar;
  25.     mutable polar *p;
  26.     };
  27.  
  28. // ... same as Listing 4 ...
  29.  
  30. double complex::rho() const
  31.     {
  32.     if (p == 0)
  33.         p = new polar(sqrt(re*re + im*im), atan2(im, re));
  34.     return p->rho;
  35.     }
  36.  
  37. double complex::theta() const
  38.     {
  39.     if (p == 0)
  40.         p = new polar(sqrt(re*re + im*im), atan2(im, re));
  41.     return p->theta;
  42.     }
  43.  
  44. complex operator+(const complex &z1, const complex &z2)
  45.     {
  46.     return complex
  47.         (z1.real() + z2.real(), z1.imag() + z2.imag());
  48.     }
  49.  
  50. int main()
  51.     {
  52.     // same as Listings 3 and 4
  53.     }
  54.