4.#
点击查看考点
生命期, 类层次
1 #include <iostream>
2
3 class A {
4 public:
5 static int count;
6
7 A() {
8 ++count;
9 }
10 A(A const& /*other*/) {
11 ++count;
12 }
13
14 virtual ~A() {
15 --count;
16 }
17 };
18
19 int A::count = 0;
20
21 class B : public A {
22 public:
23 static int count;
24
25 B() {
26 ++count;
27 }
28 B(B const& other) : A(other) {
29 ++count;
30 }
31
32 ~B() override {
33 --count;
34 }
35 };
36
37 int B::count = 0;
38
39 class C : public A {
40 public:
41 static int count;
42
43 C() {
44 ++count;
45 }
46 C(C const& other) : A(other) {
47 ++count;
48 }
49
50 ~C() {
51 --count;
52 }
53 };
54
55 int C::count = 0;
56
57 void print_count() {
58 std::cout << '(' << A::count << ", " << B::count << ", " << C::count << ")\n";
59 }
60
61 template <typename T>
62 void function() {
63 static T c1;
64 B c2;
65 A c3 = c2;
66 }
67
68 A c0;
69
70 auto main() -> int {
71 print_count();
72
73 C c1;
74 B c2;
75 A();
76 function<A>();
77 print_count();
78
79 static C c3;
80 A* c4 = new B;
81 A c5 = c1;
82 print_count();
83
84 function<A>();
85 static_cast<B*>(c4);
86 delete c4;
87 print_count();
88
89 function<B>();
90 static_cast<A>(c2);
91 print_count();
92 }