|
1 /** |
|
2 * DEREFERNCING CLASSES |
|
3 */ |
|
4 |
|
5 #include <cstdio> |
|
6 #include <cstdlib> |
|
7 #include <cmath> |
|
8 #include <ctime> |
|
9 |
|
10 #define GETRANDOM(max) (1+(int)((float)max*rand()/RAND_MAX+1.0)) |
|
11 #define MAX 6 |
|
12 |
|
13 namespace algebra { |
|
14 class Vector { |
|
15 private: |
|
16 int x; |
|
17 int y; |
|
18 |
|
19 public: |
|
20 Vector (int xx = 0, int yy = 0); |
|
21 ~Vector (); |
|
22 |
|
23 int X () { return x; } |
|
24 int Y () { return y; } |
|
25 |
|
26 Vector operator+ (Vector&); |
|
27 Vector operator- (Vector&); |
|
28 |
|
29 void vector (); |
|
30 double abs (); |
|
31 }; |
|
32 |
|
33 Vector::Vector (int xx, int yy) { |
|
34 x = xx; |
|
35 y = yy; |
|
36 } |
|
37 |
|
38 Vector::~Vector () { |
|
39 fprintf (stderr, "Removing Vector (%.3d, %.3d)\n", x, y); |
|
40 } |
|
41 |
|
42 Vector Vector::operator+ (Vector& v) { |
|
43 return Vector (x + v.X (), y + v.Y ()); |
|
44 } |
|
45 |
|
46 Vector Vector::operator- (Vector& v) { |
|
47 return Vector (x - v.X (), y - v.Y ()); |
|
48 } |
|
49 |
|
50 double Vector::abs () { |
|
51 return sqrt (x * x + y * y); |
|
52 } |
|
53 |
|
54 void Vector::vector () { |
|
55 printf ("(%.3d, %.3d)", x, y); |
|
56 } |
|
57 } |
|
58 |
|
59 using namespace algebra; |
|
60 |
|
61 int main (int argc, char **argv) |
|
62 { |
|
63 Vector *v[MAX]; |
|
64 Vector result; |
|
65 |
|
66 srand (time (NULL)); |
|
67 |
|
68 if ((MAX % 2) != 0) { |
|
69 printf ("MAX %% 2 != 0\n"); |
|
70 return EXIT_FAILURE; |
|
71 } |
|
72 |
|
73 for (int i = 0; i < MAX; i++) { |
|
74 v[i] = new Vector (GETRANDOM (100), GETRANDOM (100)); |
|
75 } |
|
76 |
|
77 for (int i = 0; i < MAX; i += 2) { |
|
78 v[i + 1]->vector (); |
|
79 printf ("+"); |
|
80 v[i]->vector (); |
|
81 printf ("="); |
|
82 result = *v[i + 1] + *v[i]; |
|
83 result.vector (); |
|
84 printf (" = %3.2f\n", result.abs ()); |
|
85 } |
|
86 |
|
87 printf ("\n"); |
|
88 |
|
89 for (int i = 0; i < MAX; i += 2) { |
|
90 v[i + 1]->vector (); |
|
91 printf ("-"); |
|
92 v[i]->vector (); |
|
93 printf ("="); |
|
94 result = *v[i + 1] - *v[i]; |
|
95 result.vector (); |
|
96 printf (" = %3.2f\n", result.abs ()); |
|
97 } |
|
98 |
|
99 printf ("\nCLEANUP\n"); |
|
100 |
|
101 for (int i = 0; i < MAX; i++) |
|
102 delete v[i]; |
|
103 |
|
104 return EXIT_SUCCESS; |
|
105 } |