多型性---建構函式和解構函式中呼叫虛擬函式
阿新 • • 發佈:2019-01-07
參考 C++ primer 15.4.5
/* 建構函式和解構函式中的虛擬函式 */ #include<iostream> using namespace std; class Base { public: //在建構函式和解構函式中呼叫虛擬函式,則執行自身型別定義的版本。原因是初始化順序:先基類後派生 Base() { Print(); } ~Base(){ Print(); }; virtual void Print() { cout<<"Base Print"<<endl; } void dd() { Print(); } }; class Derive:public Base { public: Derive() { Print(); } ~Derive(){}; virtual void Print() { i = 10; cout<<"Derive Print"<<i<<endl; } void derive_func(){} int a; private: int i; }; int main() { //new Derive(); 建立了一個派生類物件 //指標強轉,是把一個基類指標指向了一個派生類物件 //所以這個指標可以訪問派生類繼承基類的部分,自己獨有的像成員函式derive_func就不能訪問了 Base *bp = (Base *)new Derive(); cout<<"1------"<<endl; bp->Print(); cout<<"2------"<<endl; bp->dd(); cout<<"3------"<<endl; delete bp; system("pause"); return 0; }