其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
小谈虚析构函数

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

小谈虚析构函数
 一、可以先看一下下面的例子:
#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()            
 明显发现输出结果要安全得多,每一个的析构函数都调用了.这对程序的健壮性和安全性是非常重要的.
 
 




相关文章

相关软件