虚析构函数作用示例

关于虚析构函数作用示例.
首先是一个main方法驱动头文件如下:

#include "TestVirtualDestructor.h"

int main() {

Person *person = new Student;
delete person;

return 0;
}
/**
* 输出结果:
*
*1.没有使用虚析构函数的时候的输出:子类的析构函数没有调用.
调用Person的构造函数.
调用Student的构造函数.
调用Person的析构函数.
*/


相关的类文件如下:

/*
* TestVirtualDestructor.h
*
* Created on: 2011-10-12
* Author: banxi1988
*/
#include "common.h"

class Person{
public:
Person(){
cout<<"调用Person的构造函数."<<endl;
};
~Person(){
cout<<"调用Person的析构函数."<<endl;
}
};
class Student:public Person{
public:
Student(){
ptr = new int;
cout<<"调用Student的构造函数."<<endl;
}
~Student(){
delete ptr;
cout<<"调用Student的析构函数."<<endl;

}
private:
int *ptr;
};


这个时候的输出结果,可以很明显的看出没有调用子类的析构函数.
而在子类也而在删除person实例时,其实需要释放它在堆上生成的一个ptr.
.

我们将~Person声明为virtual ~Person之后运行结果如下:

/**
*
调用Person的构造函数.
调用Student的构造函数.
调用Student的析构函数.
调用Person的析构函数.

*/


所以析构函数,还是用虚的总是好的.
所以代码重构如下:

/*
* TestVirtualDestructor.h
*
* Created on: 2011-10-12
* Author: banxi1988
*/
#include "common.h"

class Person{
public:
Person(){
cout<<"调用Person的构造函数."<<endl;
};
virtual ~Person(){
cout<<"调用Person的析构函数."<<endl;
}
};
class Student:public Person{
public:
Student(){
ptr = new int;
cout<<"调用Student的构造函数."<<endl;
}
virtual ~Student(){
delete ptr;
cout<<"调用Student的析构函数."<<endl;

}
private:
int *ptr;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值