-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathZ2.CPP
99 lines (84 loc) · 1.78 KB
/
Z2.CPP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
Listing 4 - A rudimentary class for complex numbers using
"lazy" evaluation and caching for polar form
// z2.cpp
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
class complex
{
public:
complex(double r, double i);
complex(const complex &z);
complex &operator=(const complex &z);
~complex();
double real() const;
double imag() const;
double rho() const;
double theta() const;
private:
double re, im;
struct polar;
polar *p;
};
struct complex::polar
{
polar(double r, double t);
double rho, theta;
};
inline complex::polar::polar(double r, double t)
: rho(r), theta(t)
{
}
inline complex::complex(double r, double i)
: re(r), im(i), p(0)
{
}
inline complex::complex(const complex &z)
: re(z.re), im(z.im), p(0)
{
}
inline complex &complex::operator=(const complex &z)
{
re = z.re;
im = z.im;
p = 0;
return *this;
}
inline complex::~complex()
{
delete p;
}
inline double complex::real() const
{
return re;
}
inline double complex::imag() const
{
return im;
}
double complex::rho() const
{
if (p == 0)
{
complex *This = const_cast<complex *>(this);
This->p =
new polar(sqrt(re*re + im*im), atan2(im, re));
}
return p->rho;
}
double complex::theta() const
{
if (p == 0)
(polar *&)p =
new polar(sqrt(re*re + im*im), atan2(im, re));
return p->theta;
}
complex operator+(const complex &z1, const complex &z2)
{
return complex
(z1.real() + z2.real(), z1.imag() + z2.imag());
}
int main()
{
// same as Listing 3
}