首页 > 编程语言 > 详细

【C++ Primer 第15章】定义派生类析构函数

时间:2018-06-22 21:17:07      阅读:199      评论:0      收藏:0      [点我收藏+]

 学习资料

• 基类和派生类析构函数执行顺序

定义派生类析构函数

【注意】定义一个对象时先调用基类的构造函数、然后调用派生类的构造函数;析构的时候恰好相反:先调用派生类的析构函数、然后调用基类的析构函数。

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Base
 5 {
 6 public:
 7     Base()
 8     {
 9         cout << "Base contruction" << endl;
10     }
11     virtual ~Base()
12     {
13         cout << "Base deconstruction" << endl;
14     }
15 
16 };
17 
18 class Derived : public Base
19 {
20 public:
21     Derived(int i)
22     {
23         num = i;
24         cout << "Derived contruction " << num << endl;
25     }
26     virtual ~Derived()
27     {
28         cout << "Derived deconstruction" << num << endl;
29     }
30 private:
31     int num;
32 };
33 
34 int main()
35 {
36     Derived derived(1);
37 
38     Base* basePtr;
39     basePtr = new Derived(2);
40     delete basePtr;
41 }

输出结果:

技术分享图片

 

【C++ Primer 第15章】定义派生类析构函数

原文:https://www.cnblogs.com/sunbines/p/9215445.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!