虚析构和纯虚析构

--->未处理前:

#include <iostream>
#include <string>
using namespace std;
class Animal
{
public:
	Animal()
	{
		cout << "Animal类的构造函数" << endl;
	}
	~Animal()
	{
		cout << "Animal类的析构函数" << endl;
	}
	virtual void speak() = 0;
};
class Cat :public Animal
{
public:
	Cat(string name)
	{
		cout << "Cat类的构造函数" << endl;
		m_Name = new string(name);
	}
	virtual void speak()
	{
		cout << *m_Name << "小猫在说话" << endl;
	}
	~Cat()
	{
		cout << "Cat类的析构函数" << endl;
		if (m_Name != NULL)
		{
			delete m_Name;
			m_Name = NULL;
		}
	}
	string* m_Name;
};
void test01()
{
	Animal* animal = new Cat("Tom");
	animal->speak();//父类指针在析构时,不会调用子类中的析构函数,导致子类如果有堆区属性,会出 
                     现内存泄露
	delete animal;
}
int main()
{
	test01();
	return 0;
}

--->少了Cat的析构函数(在:Tom小猫在说话"的下面)

堆区数据未处理干净(子类)

----->>法1:

利用虚析构解决父类指针释放子类对象不干净的问题

----->>法2:

纯虚析构(需要声明+实现)

注意:

1.语法限制纯虚析构必须有函数实现,因为有时父类也有一些数据开辟到堆区

2.有了纯虚析构后,这个类也属于抽象类,无法实例化对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值