虚析构和纯虚析构的共性
1.可以解决父类指针释放子类对象
2.都需要具体的函数实现
虚析构和纯虚析构的区别
如果是纯虚析构,则该类属于抽象类,无法实例化对象
虚析构语法 virtual ~类名(){}
纯虚析构 virtual ~类名() = 0
纯虚析构的类外实现 类名::~类名(){}
1 #include<bits/stdc++.h> 2 #include<iostream> 3 using namespace std; 4 5 class Animal 6 { 7 public: 8 Animal() 9 { 10 cout << "Animal构造函数调用" << endl; 11 } 12 virtual void speak() = 0; 13 14 virtual~Animal() = 0; 15 }; 16 17 Animal::~Animal() 18 { 19 cout << "Animal 纯虚析构函数调用" << endl; 20 } 21 22 class Cat:public Animal 23 { 24 public: 25 Cat(string name) 26 { 27 cout << "Cat 构造函数调用" << endl; 28 m_Name = new string(name); 29 } 30 31 virtual void speak() 32 { 33 cout << *m_Name << "猫在说活" << endl; 34 } 35 36 ~Cat() 37 { 38 cout << "猫析构函数调用" << endl; 39 if(this->m_Name != NULL) 40 { 41 delete m_Name; 42 m_Name = NULL; 43 } 44 45 } 46 public: 47 string *m_Name; 48 }; 49 50 void test() 51 { 52 Animal *animal = new Cat("Tom"); 53 animal->speak(); 54 //通过父类指针去释放,会导致子类对象清理不干净,造成内存泄露 55 //解决方法是给父类增加虚析构函数 56 //虚析构函数是用来解决通过父类指针释放子类对象 57 delete animal; 58 } 59 60 int main() 61 { 62 test(); 63 return 0; 64 }