子类中有属性创建在堆区的时候,父类指针释放是无法调用子类的析构函数
解决方法:将父类中的析构函数改成虚析构或者纯虚析构
共性:
1、都可以解决父类的释放问题
2、都要有具体实现
#include<iostream>
#include<string>
using namespace std;
class Animal {
public:
Animal(){
cout << "Animal的构造函数调用" << endl;
}
virtual ~Animal() = 0;
virtual void speak() = 0;
public:
string *m_name;
};
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;
}
}
};
void test() {
Animal* animal = new cat("tom");
animal->speak();
delete animal;
}
int main() {
test();
return 0;
}