構造函數中調用virtual 函數
阿新 • • 發佈:2018-05-19
code 分享 amp mage TP pan 調用 UC 結果
#include<iostream> using namespace std; class myclass { public: virtual void hello(){cout<<"hello from myclass"<<endl;} virtual void bye(){cout<<"bye from myclass"<<endl;} }; class son:public myclass { public: void hello(){cout<<"hello from my son"<<endl;}; son(){hello();}; ~son(){bye();}; }; class grandson:public son { public: void hello(){cout<<"hello from grandson"<<endl;}; grandson(){cout<<"constructing grandson"<<endl;}; ~grandson(){cout<<"destructing grandson"<<endl;}; }; int main() { grandson gson; son*pson; pson=&gson; pson->hello(); return 0; }
運行結果
1 gson 先創建 son son() 中靜態鏈接 son::hello() 2 gson 創建 3 gson->hello() 動態連接到 grandson::hello() 4 gson 的析構函數 5 gson 中 son 的析構,~son 鏈接到 myclass() ::bye()
在構造函數和析構函數中調用虛函數時 他們調用的函數是自己的類或基類中定義的函數 不會等到運行時 才決定調用自己還是派生的函數
構造函數中調用virtual 函數