Skip to content

Commit 6456c3c

Browse files
authored
Fix some errors in Inheritance.md (ronreiter#691)
Fix imaginary part of the `c1` in the expected output. Add detail to the solution.
1 parent ca419b1 commit 6456c3c

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

tutorials/learn-cpp.org/en/Inheritance.md

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ Tutorial Code
6868
int main()
6969
{
7070
Complex c1(15, 15), c2 (100, 100);
71+
cout << endl;
7172
return 0;
7273
}
7374

@@ -76,11 +77,10 @@ Expected Output
7677

7778
Forming...x (real): 15 15 y (imag): 30 30
7879
Forming...x (real): 100 100 y (imag): 200 200
79-
8080
c1: (Point) x:100 y:200
8181
c2: x:15 y:30
8282

83-
c1: x (real): 100 100 y (imag): 200 100
83+
c1: x (real): 100 100 y (imag): 200 200
8484
c2: x (real): 15 15 y (imag): 30 30
8585

8686
Solution
@@ -94,22 +94,54 @@ Solution
9494
std::ostream& operator<<(std::ostream& out, const Point& c);
9595

9696
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+
97121
std::ostream& operator<<(std::ostream& out, const Complex& c)
98122
{
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;
101126
}
102127

103128
int main()
104129
{
105130
Complex c1(15, 30), c2 (100, 200);
106131
Point& p_c1 = c1; Point& p_c2 = c2;
132+
cout << endl;
107133
108134
Swap (p_c1, p_c2); // swapping Complex objects as Point objects
109135
110-
cout << "c1: (Point)" << p_c1 << "c2: " << p_c2 << endl;
136+
cout << "c1: (Point) " << p_c1 << "c2: " << p_c2 << endl;
111137
cout << "c1: " << c1 << "c2: " << c2 << endl;
112138
113139
return 0;
114140
}
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

Comments
 (0)