多态使用时,若子类中有属性开辟到堆区,那么父类指针在释放时无法调用子类的析构代码
解决方式:将父类中的析构函数改为虚析构或纯虚析构
虚析构和纯虚析构共性:
可以解决父类指针释放子类对象
- 都需要具体的函数实现
- 区别:若是纯虚析构,该类属于抽象类,不能实例化对象
虚析构语法:
virtual ~类名(){}
纯虚析构语法:
virtual ~类名()=0;
类名::~类名(){}
#include<iostream>
using namespace std;
#include<string>
class Animal {
public:
Animal() {
cout << "animal构造函数的调用" << endl;
}
virtual void Speak() = 0;//虚析构函数
virtual ~Animal() = 0;
};
Animal::~Animal()
{
cout << "Animal纯虚析构函数的调用" << endl;
}
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 (this->m_Name != NULL)
{
delete m_Name;
m_Name = NULL;
}
}
public:
string* m_Name;
};
void test()
{
Animal* animal = new Cat("tom");
animal->Speak();
delete animal;
}
int main(){
test();
system("pause");
return 0;
}