C++虛析構(gòu)函數(shù)基本內(nèi)容概述
今天,我們將會在這篇文章中為大家詳細介紹一下C++虛析構(gòu)函數(shù)的一些基本知識。相信對于剛剛接觸C++編程語言的初學者們現(xiàn)在急需要諸如這方面的基礎知識的講解內(nèi)容,以加大自己對這一語言的認知。#t#
C++的多態(tài)性是通過虛函數(shù)來實現(xiàn)的,虛函數(shù)的出現(xiàn)使得動態(tài)鏈接成為可能。
基于構(gòu)造函數(shù)的特點,不能將構(gòu)造函數(shù)定義為虛函數(shù),但可以將析構(gòu)函數(shù)定義為虛函數(shù)。當派生類的對象從內(nèi)存中撤銷時,會先調(diào)用派生類的析構(gòu)函數(shù),然后自動調(diào)用基類的析構(gòu)函數(shù),如此看來析構(gòu)函數(shù)也沒有必要定義為虛函數(shù)。
但是考慮如下這種情況,如果使用基類指針指向派生類的對象,而這個派生類對象恰好是用new運算創(chuàng)建的,這種情況下會如何呢?當程序使用delete運算撤銷派生類對象時,這時只會調(diào)用基類的析構(gòu)函數(shù),而沒有調(diào)用派生類的析構(gòu)函數(shù)。如果使用的是虛析構(gòu)函數(shù)的話,就不一樣了,所以定義虛析構(gòu)函數(shù)有時候還是很有必要的。下面這段程序就說明了上面的問題:
沒有定義虛C++虛析構(gòu)函數(shù)時,code如下:
- #include < iostream>
- using namespace std;
- class A
- {
- public:
- A(){}
- ~A()
- {
- cout< < "A::destructor"< < endl;
- }
- };
- class B:public A
- {
- public:
- B(){}
- ~B()
- {
- cout< < "B::destructor"< < endl;
- }
- };
- int main()
- {
- A *pA = new B;
- //
- delete pA;
- return 0;
- }
輸出的是A::destructor
這說明delete pA只是調(diào)用了基類A的析構(gòu)函數(shù),而沒有調(diào)用子類B的析構(gòu)函數(shù),這不是我們所想要的。而把基類A的析構(gòu)函數(shù)定義為虛函數(shù)后,就可以達到了我們所想要的效果了。code如下:
- #include < iostream>
- using namespace std;
- class A
- {
- public:
- A(){}
- virtual ~A()
- {
- cout< < "A::destructor"< < endl;
- }
- };
- class B:public A
- {
- public:
- B(){}
- ~B()
- {
- cout< < "B::destructor"< < endl;
- }
- };
- int main()
- {
- A *pA = new B;
- //
- delete pA;
- return 0;
- }
輸出如下:
B::destrutor
A::destrutor
以上就是對C++虛析構(gòu)函數(shù)的相關(guān)介紹。