现在的位置: 首页 > 综合 > 正文

在派生类中增加函数

2018年04月14日 ⁄ 综合 ⁄ 共 834字 ⁄ 字号 评论关闭

#include <iostream>
using namespace std;
class father
{
public:
 void smart(){cout<<"父亲很聪明!"<<endl;}
 //virtual void beautiful(){}
 virtual ~father(){cout<<"析构父亲类!"<<endl;}
};
class son:public father
{
public:
 void beautiful(){cout<<"儿子也很英俊!"<<endl;}
 ~son(){cout<<"析构儿子类!"<<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();
   /*
   将基类的指针转换为派生类的指针
   RTTI运行时类型信息
   两种方法:dynamic_cast和typeid
   Project->Settings->C/C++->Category->C Language->
   Enable Run-Time Type lnformation (RTTI)->OK
   */
   pf->smart();
   delete pf;
   break;
  default:cout<<"请输入从0到2之前的数"<<endl;
  }
  if (quit==true)
  {
   break;
  }
 }
 cout<<"程序结束!"<<endl;
 return 0;
}

【上篇】
【下篇】

抱歉!评论已关闭.