析構函數定義爲虛函數

析構函數執行時先調用派生類的析構函數,其次才調用基類的析構函數。如果析構函數不是虛函數,而程序執行時又要通過基類的指針去銷燬派生類的動態對象,那麼用delete銷燬對象時,只調用了基類的析構函數,未調用派生類的析構函數。這樣會造成銷燬對象不完全。

#include<iostream.h>
#include<stdlib.h>

class CPerson
{
public:
   virtual ~CPerson();       //基類的析構函數必須聲明爲虛函數,否則

                                用delete銷燬對象時會出錯
protected:
 char * m_lpszName;
 char * m_lpszSex;
};

class CStudent:public CPerson
{
public:
 ~CStudent();              //virtual可加也可不加
protected:
 int m_iNumjber;           //學號
};

CPerson::~CPerson()
{
 cout<<"~CPerson!"<<endl;
}


CStudent::~CStudent()
{
 cout<<"~CStudent!"<<endl;
}

void main()
{
 CPerson * poCPerson = new CStudent;        //構造一個CStudent的動態對象
 if(NULL==poCPerson)
 {
  exit(0);
 }
 delete poCPerson;
 cout<<"CStudent對象已經完成析構"<<endl;     //如果析構函數是非虛函數,

                                               那麼CStudent對象就未析構完
 CStudent oCStudent;
}

 

輸出:

~Student!

~CPerson!

CStudent對象已經完成析構

~Student!

~CPerson!

 

如果去掉~CPerson()前面的virtual,且將“CStudent對象已經完成析構”改爲“CStudent對象未完成析構”。程序的執行結果爲:

~CPerson!

CStudent對象未完成析構

~Student!

~CPerson!


參考:http://359611946.blog.163.com/blog/static/1161900200976115331797/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章