[C++基础]023_为什么要将基类的析构函数声明为Virtual?
1 #include <iostream> 2 using namespace std; 3 4 class Father{ 5 6 public: 7 ~Father(){ 8 cout<<"Father's Desconstruct Called."<<endl; 9 } 10 }; 11 12 class Son : public Father{ 13 public: 14 ~Son(){ 15 cout<<"Son's Desconstruct Called."<<endl; 16 } 17 }; 18 19 int main(){ 20 21 Father *f = new Son(); 22 delete f; 23 24 system("pause"); 25 26 return 0; 27 }
上面的代码,用父类指针指向new出来来的之类对象,这样是没问题的,接着,对这个父类指针变量进行了delete操作。上面的输出结果是什么呢?
Father's Desconstruct Called.
可见,子类的析构函数没有被调用,那如果子类中new了内存,那么那块内存就丢了。如何保证在删除父类指针的时候,子类的析构函数也被调用呢?看如下代码:
1 #include <iostream> 2 using namespace std; 3 4 class Father{ 5 6 public: 7 virtual ~Father(){ 8 cout<<"Father's Desconstruct Called."<<endl; 9 } 10 }; 11 12 class Son : public Father{ 13 public: 14 ~Son(){ 15 cout<<"Son's Desconstruct Called."<<endl; 16 } 17 }; 18 19 int main(){ 20 21 Father *f = new Son(); 22 delete f; 23 24 system("pause"); 25 26 return 0; 27 }
输出是什么呢?
Son's Desconstruct Called. Father's Desconstruct Called.
这就是动态联编的析构函数,至于为什么这样就可以调用子类的析构函数了,这就牵涉到另一个概念:虚函数表。具体请参照:http://blog.csdn.net/hairetz/article/details/4137000