22
33// READ: 派生类 <https://zh.cppreference.com/w/cpp/language/derived_class>
44
5+ static int i = 0 ;
6+
57struct X {
68 int x;
79
810 X (int x_) : x(x_) {
9- std::cout << " X(" << x << ' )' << std::endl;
11+ std::cout << ++i << " . " << " X(" << x << ' )' << std::endl;
1012 }
1113 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;
1315 }
1416 ~X () {
15- std::cout << " ~X(" << x << ' )' << std::endl;
17+ std::cout << ++i << " . " << " ~X(" << x << ' )' << std::endl;
1618 }
1719};
1820struct A {
1921 int a;
2022
2123 A (int a_) : a(a_) {
22- std::cout << " A(" << a << ' )' << std::endl;
24+ std::cout << ++i << " . " << " A(" << a << ' )' << std::endl;
2325 }
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;
2628 }
2729 ~A () {
28- std::cout << " ~A(" << a << ' )' << std::endl;
30+ std::cout << ++i << " . " << " ~A(" << a << ' )' << std::endl;
2931 }
3032};
3133struct B : public A {
3234 X x;
3335
3436 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;
3638 }
3739 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;
3941 }
4042 ~B () {
41- std::cout << " ~B(" << a << " , X(" << x.x << " ))" << std::endl;
43+ std::cout << ++i << " . " << " ~B(" << a << " , X(" << x.x << " ))" << std::endl;
4244 }
4345};
4446
@@ -52,6 +54,7 @@ int main(int argc, char **argv) {
5254 static_assert (sizeof (A) == ?, " There is an int in A" );
5355 static_assert (sizeof (B) == ?, " B is an A with an X" );
5456
57+ i = 0 ;
5558 std::cout << std::endl
5659 << " -------------------------" << std::endl
5760 << std::endl;
@@ -65,5 +68,10 @@ int main(int argc, char **argv) {
6568 // THINK: 这样的代码是“安全”的吗?
6669 // NOTICE: 真实场景中不太可能出现这样的代码
6770
71+ i = 0 ;
72+ std::cout << std::endl
73+ << " -------------------------" << std::endl
74+ << std::endl;
75+
6876 return 0 ;
6977}
0 commit comments