題目描述:C++中子類父類構造函數和析構函數的執行
代碼如下:
1)當父類析構函數爲虛函數時:
<span style="font-size:14px;">#include<iostream>
using namespace std;
class Father{
public:
Father(){
cout << "This is the father Structor !" << endl;
}
//父類析構函數爲虛函數
virtual ~Father(){
cout << "This is the father Destructor !" << endl;
}
virtual void Find(){
cout << "This is the father Find !" << endl;
}
};
class Son :public Father{
public:
Son(){
cout << "This is the son Structor !" << endl;
}
~Son(){
cout << "This is the son Desturctor!" << endl;
}
void Find(){
cout << "This is the son Find !" << endl;
}
};
int main(){
cout << "-----------Father* a = new Father()------------" << endl;
Father*a = new Father();
a->Find();
delete a;
cout << endl;
cout << "-----------Father* b = new Son()------------" << endl;
Father*b = new Son();
b->Find();
delete b;
cout << endl;
cout << "-----------Son* c = new Son()------------" << endl;
Son*c = new Son();
c->Find();
delete c;
system("pause");
return 0;
}</span>
代碼運行結果:
結果分析:
1.初始Father*a = new Father();
a->Find();
delete a;
此時,先執行Father類構造函數,其次執行父類Find函數,最後執行父類的析構函數。
2. Father*b = new Son();
b->Find();
delete b;
因爲是定義new Son()類型對象,所以首先執行父類的構造函數,其次執行子類Son的構造函數,執行Find函數時,也是執行子類的Find。
執行析構函數時,是看對象b的類型,b的類型是Father類型的,但是如果父類的析構函數是虛函數時,會首先到虛函數映射表中查找父類析構函數的實例函數,執行完以後,再執行父類的析構函數(父類的析構函數不是純虛函數)。
3. Son*c = new Son();
c->Find();
delete c;
先執行父類構造函數,再執行子類構造函數
執行析構函數時,先執行子類析構函數,再執行父類的析構函數。
2)當父類析構函數不是虛函數時:
#include<iostream>
using namespace std;
class Father{
public:
Father(){
cout << "This is the father Structor !" << endl;
}
//父類析構函數不是虛函數
~Father(){
cout << "This is the father Destructor !" << endl;
}
virtual void Find(){
cout << "This is the father Find !" << endl;
}
};
class Son :public Father{
public:
Son(){
cout << "This is the son Structor !" << endl;
}
~Son(){
cout << "This is the son Desturctor!" << endl;
}
void Find(){
cout << "This is the son Find !" << endl;
}
};
int main(){
cout << "-----------Father* a = new Father()------------" << endl;
Father*a = new Father();
a->Find();
delete a;
cout << endl;
cout << "-----------Father* b = new Son()------------" << endl;
Father*b = new Son();
b->Find();
delete b;
cout << endl;
cout << "-----------Son* c = new Son()------------" << endl;
Son*c = new Son();
c->Find();
delete c;
system("pause");
return 0;
}
結果如下:分析:從對比可以發現,執行Father*b = new Son();
b->Find();
delete b;
時結果會有不同。