小谈虚析构函数

可以先看一下下面的例子:
#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() 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值