--->未处理前:
#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.有了纯虚析构后,这个类也属于抽象类,无法实例化对象