小谈虚析构函数

王朝other·作者佚名  2006-01-09
宽屏版  字体: |||超大  

小谈虚析构函数

一、可以先看一下下面的例子:

#include <iostream>

using namespace std;

class Mother

{

public:

//最主要的区别就是在析构函数前加没加virtual;分别观察结果(A和B两种情况)

~Mother(){ cout << "~Mother" << endl;}

//virtual ~Mother(){cout << "~Mother()" << endl;}//

};

class Son :public Mother

{

public:

~Son(){cout << "~Son()" << endl;}

};

class Grandson:public Son

{

public :

~Grandson()

{cout << "~Grandson()" << endl;}

};

int main()

{

Mother *one = new Son ;

Mother *two = new Grandson;

Son *three = new Grandson;

Grandson four;

delete one;

delete two;

delete three;

system("pause");

return 0;

}

A:当基类Mother的析构函数不是virtual 输出情况为:

~Mother()

~Mother()

~Son()

~Mother()

~Grandson()

~Son()

~Mother()

第一行是delete one输出的结果;第二行是delete two的输出结果;第三.四行是delete three的输出结果;

第5~7行是Grandson four的虚构函数

B:当基类Mother的析构函数是virtual 输出情况为:

~Son()

~Mother()

~Grandson()

~Son()

~Mother()

~Grandson()

~Son()

~Mother()

~Grandson()

~Son()

~Mother()

明显发现输出结果要安全得多,每一个的析构函数都调用了.这对程序的健壮性和安全性是非常重要的.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有