C++虚析构函数的作用

来源:互联网 发布:React双向数据绑定原理 编辑:程序博客网 时间:2024/05/21 00:18

1、作用

为了在实现多态的时候不造成内存泄露,

如果基类析构函数前不加vitual,派生类对象被销毁后,只会调用基类的析构函数,而不会去调用派生类的析构函数。

 

2、对于正常的函数,如果基类中声明为virtual,则派生类可以不用再写virtual

 

[c-sharp] view plaincopy
  1. // CPPTest.cpp : Defines the entry point for the console application.  
  2. //  
  3. #include "stdafx.h"  
  4. class Base  
  5. {  
  6. public:  
  7.     Base(){}  
  8.     virtual ~Base()  
  9.     {  
  10.         printf("Base Destructor!/n");  
  11.     }  
  12.     virtual void Func()  
  13.     {  
  14.         printf("Base Func!/n");  
  15.     }  
  16. private:  
  17.     int m_iData;  
  18. };  
  19. class Derived : public Base  
  20. {  
  21. public:  
  22.     Derived(){}  
  23.     ~Derived()  
  24.     {  
  25.         printf("Derived Destructor!/n");  
  26.     }  
  27.     void Func()  
  28.     {  
  29.         printf("Derived Func!/n");  
  30.     }  
  31. };  
  32. class Derived2 : public Derived  
  33. {  
  34. public:  
  35.     Derived2(){}  
  36.     ~Derived2()  
  37.     {  
  38.         printf("Derived2 Destructor!/n");  
  39.     }  
  40.     void Func()  
  41.     {  
  42.         printf("Derived2 Func!/n");  
  43.     }  
  44. };  
  45.   
  46. int main(int argc, char* argv[])  
  47. {  
  48.     Base *pb = new Base;  
  49.     pb->Func();  
  50.     Base *pd = new Derived;  
  51.     pd->Func();  
  52.     Base *pd2 = new Derived2;  
  53.     pd2->Func();  
  54.     delete pb;  
  55.     delete pd;  
  56.     delete pd2;  
  57.     return 0;  
  58. }  
 

 

结果:

Base Func!

Derived Func!

Derived2 Func!

Base Destructor!

Derived Destructor!

Base Destructor!

Derived2 Destructor!

Derived Destructor!

Base Destructor!

 

0 0