虚析构和纯虚析构

虚析构和纯虚析构

多态使用时,如果子类有属性开辟到堆区,那么父类指针在释放时无法带调用到子类的析构代码
解决方式:将父类的析构函数改为纯虚析构或者虚析构

虚析构和纯虚析构的共性:

1.可以解决父类指针释放子类对象
2.都必须要有具体的函数实现

虚析构和纯虚析构的区别:
如果是纯虚析构,该类属于抽象类,无法实例化对象

#include<iostream>
#include<string>
using namespace std;
class animal {
public:
	//构造函数
	animal()
	{
		cout << "animal的构造函数调用" << endl;
	}
    //纯虚函数
	virtual void speak()
	{
		cout << "动物在说话" << endl;
	}
	//虚析构
	virtual ~animal()
	{
		cout << "animal的析构函数调用" << endl;
	}
};
class cat:public animal {
public:
	//构造函数
	cat(string name) {
		this->name = new string(name); //在堆区创建内存
		cout << "cat的构造函数调用" << endl;
	}
	void speak()
	{
		cout <<*name<< "小猫在说话" << endl;
	}
	//写一个析构函数释放堆区内存
	virtual ~cat() {
		if (name != NULL)
		{
			cout << "cat的析构函数调用" << endl;
			delete name; //释放堆区内存
			name = NULL;
		}
	}
	string* name;
};
void test()
{
	animal* a =new cat("tom");
	a->speak();
	delete a; //如果不在析构函数前加virtual,就只会调用父类析构函数
}
int main()
{
	test();
	system("pause");
	return 0;
}

纯虚析构写法:virtual ~animal()=0
纯虚析构定义实现和虚析构一样:
animal::~animal(){}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值