2
2
3
3
// READ: 派生类 <https://zh.cppreference.com/w/cpp/language/derived_class>
4
4
5
+ static int i = 0 ;
6
+
5
7
struct X {
6
8
int x;
7
9
8
10
X (int x_) : x(x_) {
9
- std::cout << " X(" << x << ' )' << std::endl;
11
+ std::cout << ++i << " . " << " X(" << x << ' )' << std::endl;
10
12
}
11
13
X (X const &other) : x(other.x) {
12
- std::cout << " X(X const &) : x(" << x << ' )' << std::endl;
14
+ std::cout << ++i << " . " << " X(X const &) : x(" << x << ' )' << std::endl;
13
15
}
14
16
~X () {
15
- std::cout << " ~X(" << x << ' )' << std::endl;
17
+ std::cout << ++i << " . " << " ~X(" << x << ' )' << std::endl;
16
18
}
17
19
};
18
20
struct A {
19
21
int a;
20
22
21
23
A (int a_) : a(a_) {
22
- std::cout << " A(" << a << ' )' << std::endl;
24
+ std::cout << ++i << " . " << " A(" << a << ' )' << std::endl;
23
25
}
24
- A (A const &other) : A (other.a) {
25
- std::cout << " A(A const &) : a(" << a << ' )' << std::endl;
26
+ A (A const &other) : a (other.a) {
27
+ std::cout << ++i << " . " << " A(A const &) : a(" << a << ' )' << std::endl;
26
28
}
27
29
~A () {
28
- std::cout << " ~A(" << a << ' )' << std::endl;
30
+ std::cout << ++i << " . " << " ~A(" << a << ' )' << std::endl;
29
31
}
30
32
};
31
33
struct B : public A {
32
34
X x;
33
35
34
36
B (int b) : A(1 ), x(b) {
35
- std::cout << " B(" << a << " , X(" << x.x << " ))" << std::endl;
37
+ std::cout << ++i << " . " << " B(" << a << " , X(" << x.x << " ))" << std::endl;
36
38
}
37
39
B (B const &other) : A(other.a), x(other.x) {
38
- std::cout << " B(B const &) : A(" << a << " ), x(X(" << x.x << " ))" << std::endl;
40
+ std::cout << ++i << " . " << " B(B const &) : A(" << a << " ), x(X(" << x.x << " ))" << std::endl;
39
41
}
40
42
~B () {
41
- std::cout << " ~B(" << a << " , X(" << x.x << " ))" << std::endl;
43
+ std::cout << ++i << " . " << " ~B(" << a << " , X(" << x.x << " ))" << std::endl;
42
44
}
43
45
};
44
46
@@ -52,6 +54,7 @@ int main(int argc, char **argv) {
52
54
static_assert (sizeof (A) == ?, " There is an int in A" );
53
55
static_assert (sizeof (B) == ?, " B is an A with an X" );
54
56
57
+ i = 0 ;
55
58
std::cout << std::endl
56
59
<< " -------------------------" << std::endl
57
60
<< std::endl;
@@ -65,5 +68,10 @@ int main(int argc, char **argv) {
65
68
// THINK: 这样的代码是“安全”的吗?
66
69
// NOTICE: 真实场景中不太可能出现这样的代码
67
70
71
+ i = 0 ;
72
+ std::cout << std::endl
73
+ << " -------------------------" << std::endl
74
+ << std::endl;
75
+
68
76
return 0 ;
69
77
}
0 commit comments