-->

C++_练习—继承_构造析构

2020-09-16 15:08发布

构造析构


 

继承与构造析构

在子类对象构造时,需要调用父类构造函数对其继承得来的成员进行初始化
在子类对象析构时,需要调用父类析构函数对其继承得来的成员进行清理

 

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class info1 {
 6 public:
 7     info1(int a) {
 8         num1 = a;
 9         cout << "info1 构造自动调用" << endl;
10     }
11 
12     ~info1() {
13         cout << "info1 析构自动调用" << endl;
14     }
15 
16 
17 protected:
18     int num1;
19 
20 private:
21     int age1;
22 
23 };
24 
25 
26 class info: public info1 {
27 public:
28     info():info1(66){
29         cout << num1 << endl;
30         cout << "info 构造自动调用" << endl;
31     }
32     
33     ~info() {
34         cout << "info 析构自动调用" << endl;
35     }
36 
37 protected:
38     int num2;
39 
40 private:
41     int age2;
42 
43 };
44 
45 
46 int main(void)
47 {
48     info text;
49 
50 
51     system("pause");
52 
53     return 0;
54 }

 

 构造调用顺序:先基类构造,在派生类构造!

 

 

 

笔记


 

标签: