和構(gòu)造函數(shù)類似,析構(gòu)函數(shù)也是不能被繼承的。
創(chuàng)建派生類對(duì)象時(shí),構(gòu)造函數(shù)的調(diào)用順序和繼承順序相同,先執(zhí)行基類構(gòu)造函數(shù),然后再執(zhí)行派生類的構(gòu)造函數(shù)。但是對(duì)于析構(gòu)函數(shù),調(diào)用順序恰好相反,即先執(zhí)行派生類的析構(gòu)函數(shù),然后再執(zhí)行基類的析構(gòu)函數(shù)。
請(qǐng)看下面的例子:
#include <iostream>using namespace std;class A{public: A(){cout<<"A constructor"<<endl;} ~A(){cout<<"A destructor"<<endl;}};class B: public A{public: B(){cout<<"B constructor"<<endl;} ~B(){cout<<"B destructor"<<endl;}};class C: public B{public: C(){cout<<"C constructor"<<endl;} ~C(){cout<<"C destructor"<<endl;}};int main(){ C test; return 0;}運(yùn)行結(jié)果:
A constructorB constructorC constructorC destructorB destructorA destructor
從運(yùn)行結(jié)果可以很明顯地看出來(lái),構(gòu)造函數(shù)和析構(gòu)函數(shù)的執(zhí)行順序是相反的。
需要注意的是,一個(gè)類只能有一個(gè)析構(gòu)函數(shù),調(diào)用時(shí)不會(huì)出現(xiàn)二義性,所以析構(gòu)函數(shù)不需要顯式地調(diào)用。
新聞熱點(diǎn)
疑難解答