建構函式執行順序
阿新 • • 發佈:2018-12-22
通過示例說明:
#include <iostream> class Base { public: Base(); virtual void f(); virtual void func(); }; Base::Base() { std::cout << "Base construct" << std::endl; f(); } void Base::func() { f(); } void Base::f() { std::cout << "Base f() called" << std::endl; } class Devied : public Base { public: Devied(); void f(); }; Devied::Devied() { std::cout << "Devied construct" << std::endl; } void Devied::f() { std::cout << "Devied f() called" << std::endl; } //by zhaocl int main() { Devied d; d.func(); system( "pause" ); return 0; }
執行結果:
Base construct
Base f() called
Devied construct
Devied f() called
基礎知識點總結:
1、建構函式先父類再子類,所以先 Base 再 Decied
2、Base 中呼叫 f() ,該函式是一個虛擬函式,所以一般會呼叫 Devied::f(),因為物件d是Devied型別的,檢視Base::Func() 中的函式呼叫可以得出結果。但是,如果是在Base的建構函式中呼叫,因為此時Devied還沒構造,物件還不是Devied型別,所以呼叫的是Base::f(),這個檢視建構函式中的函式呼叫可以看出。