C++学习记录(三)析构函数,初始化

这是第三天的学习记录

 1 #include <iostream>
 2 
 3 using namespace std;
 4 class B
 5 {
 6 public:
 7     B() { cout << "B construction !" << endl; }
 8     ~B() { cout << "B deconstruction !" << endl; }
 9 };
10 
11 class A
12 {
13     B* b;
14 public:
15     A()
16     {
17         cout << "A construction !" << endl;
18         b = new B;
19     }
20     // 析构函数的定义格式,用于释放类中指针指向堆区中的空间,对象销毁时自动调用
21     ~A()
22     {
23         cout << "A deconstruction !" << endl;
24         delete b;
25     }
26 };
27 
28 
29 int main()
30 {
31     // 析构函数专门用于清理类中有指针的成员(该成员指向堆区的情况)
32     //A a;
33     A* pa = new A;
34     delete pa;
35     cout << "Hello World!" << endl;
36     return 0;
37 }
 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class B
 6 {
 7     B()
 8     {
 9         cout << "B is construction !" << endl;
10     }
11     ~B()
12     {
13         cout << "B is deconstruction !" << endl;
14     }
15 };
16 class A
17 {
18 private:
19     const int a;        // 只读变量要在构造时初始化
20     static int b;       // 静态成员变量,必需在类外初始化,且只能初始化一次
21 public:
22     // 初始化列表是构造函数的特殊语法,调用时机先于构造函数
23     A():a(100)
24     {
25         cout << "A is construction !" << endl;
26     }
27     ~A()
28     {
29         cout << "A is deconstruction !" << endl;
30     }
31     int getAInfo()
32     {
33         return a;
34     }
35     int getBInfo()
36     {
37         return b;
38     }
39 
40 };
41 
42 // 静态变量初始化格式:类外,main函数前
43 int A::b = 200;
44 
45 int main()
46 {
47     A a;
48     cout << a.getAInfo() << endl;
49     cout << a.getBInfo() << endl;
50 
51     cout << "Hello World!" << endl;
52     return 0;
53 }

 

posted @ 2022-05-07 08:15  Z_He  阅读(44)  评论(0编辑  收藏  举报