在派生类中增加函数
#include <iostream>
using namespace std;
class father
{
public:
?void smart(){cout<<"父親很聰明!"<<endl;}
?//virtual void beautiful(){}
?virtual ~father(){cout<<"析構(gòu)父親類!"<<endl;}
};
class son:public father
{
public:
?void beautiful(){cout<<"兒子也很英俊!"<<endl;}
?~son(){cout<<"析構(gòu)兒子類!"<<endl;}
};
int main()
{
?father*pf;
?int choice=0;
?while(choice<99)
?{
??bool quit=false;
??cout<<"[0]退出[1]父親[2]兒子:";
??cin>>choice;
??switch (choice)
??{
??case 0:
???quit=true;
???break;
??case 1:
???pf=new father;
???//pf->beautiful();
???break;
??case 2:
???pf=new son;
???dynamic_cast<son*>(pf)->beautiful();
???/*
???將基類的指針轉(zhuǎn)換為派生類的指針
???RTTI運(yùn)行時(shí)類型信息
???兩種方法:dynamic_cast和typeid
???Project->Settings->C/C++->Category->C Language->
???Enable Run-Time Type lnformation (RTTI)->OK
???*/
???pf->smart();
???delete pf;
???break;
??default:cout<<"請(qǐng)輸入從0到2之前的數(shù)"<<endl;
??}
??if (quit==true)
??{
???break;
??}
?}
?cout<<"程序結(jié)束!"<<endl;
?return 0;
}
總結(jié)