#include<iostream>
#include<string>
using namespace std;
//纯虚构函数或虚析构的存在是为了解决子类中有变量开辟到堆区后,子类虚构函数不访问的问题
class Animal {
public:
Animal() {
cout <<"Animal的构造函数" << endl;
}
/*virtual ~Animal(){
cout << "Animal的析构函数" << endl;
}*/
//纯析构函数
virtual ~Animal() = 0;
virtual void speak() {
cout << "动物在叫" << endl;
}
};
Animal::~Animal() {
cout << "Animal的纯析构函数" << endl;
}
class Cat : public Animal {
public:
string* m_Name;
Cat(string name) {
cout << "猫的函数" << endl;
m_Name = new string (name); //将数据开辟到堆区
}
~Cat() {
if (m_Name != NULL) {
cout << "猫的析构函数" << endl;
delete m_Name;
m_Name = NULL;
}
}
void speak() {
cout << *m_Name << "猫在叫" << endl;
}
};
static void test() {
Animal* animal = new Cat("缅因");
animal->speak();
//父类指针在析构时不会调用子类中的析构函数,若子类有堆区属性会造成内存泄露
delete animal;
}
int main() {
test();
return 0;
}
虚析构函数和纯虚析构函数
于 2024-04-27 16:26:49 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)