虚析构和纯虚析构
多态使用时,如果子类有属性开辟到堆区,那么父类指针在释放时无法带调用到子类的析构代码
解决方式:将父类的析构函数改为纯虚析构或者虚析构
虚析构和纯虚析构的共性:
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(){}