@@ -68,6 +68,7 @@ Tutorial Code
68
68
int main()
69
69
{
70
70
Complex c1(15, 15), c2 (100, 100);
71
+ cout << endl;
71
72
return 0;
72
73
}
73
74
@@ -76,11 +77,10 @@ Expected Output
76
77
77
78
Forming...x (real): 15 15 y (imag): 30 30
78
79
Forming...x (real): 100 100 y (imag): 200 200
79
-
80
80
c1: (Point) x:100 y:200
81
81
c2: x:15 y:30
82
82
83
- c1: x (real): 100 100 y (imag): 200 100
83
+ c1: x (real): 100 100 y (imag): 200 200
84
84
c2: x (real): 15 15 y (imag): 30 30
85
85
86
86
Solution
@@ -94,22 +94,54 @@ Solution
94
94
std::ostream& operator<<(std::ostream& out, const Point& c);
95
95
96
96
class Complex;
97
+
98
+ template<typename T>
99
+ void Swap(T &a, T &b) { T temp = a; a = b; b = temp; }
100
+
101
+ class Point {
102
+ public:
103
+ int x, y;
104
+
105
+ Point (int c1, int c2) { x = c1; y = c2;}
106
+ Point& operator=(Point rhs) {
107
+ x = rhs.x; y = rhs.y;
108
+ return *this;
109
+ }
110
+ };
111
+
112
+ class Complex : public Point {
113
+ private:
114
+ int &real, &imag;
115
+ public:
116
+ Complex(int r, int i) : Point (r, i), real (x), imag (y)
117
+ { cout << "Forming..." << *this; }
118
+ friend std::ostream& operator<<(std::ostream& out, const Complex& c);
119
+ };
120
+
97
121
std::ostream& operator<<(std::ostream& out, const Complex& c)
98
122
{
99
- // write obj to stream
100
-
123
+ // write obj to stream
124
+ out << "x (real): " << c.x << " " << c.real
125
+ << " y (imag): " << c.y << " " << c.imag << endl;
101
126
}
102
127
103
128
int main()
104
129
{
105
130
Complex c1(15, 30), c2 (100, 200);
106
131
Point& p_c1 = c1; Point& p_c2 = c2;
132
+ cout << endl;
107
133
108
134
Swap (p_c1, p_c2); // swapping Complex objects as Point objects
109
135
110
- cout << "c1: (Point)" << p_c1 << "c2: " << p_c2 << endl;
136
+ cout << "c1: (Point) " << p_c1 << "c2: " << p_c2 << endl;
111
137
cout << "c1: " << c1 << "c2: " << c2 << endl;
112
138
113
139
return 0;
114
140
}
115
-
141
+
142
+ std::ostream& operator<<(std::ostream& out, const Point& c)
143
+ {
144
+ out<< "x:" << c.x << " ";
145
+ out<< "y:" << c.y << "\n";
146
+ return out;
147
+ }
0 commit comments