类成员函数指针

#include <iostream>
using namespace std;
class human //抽象类human
{
   public:
   virtual void run()=0; //纯虚函数run
   virtual void eat()=0; //纯虚函数eat
};
class mother:public human //派生类mother从抽象类human继承
{
   public:
   void run(){cout<<"母亲跑百米要花二十秒\n";} //覆盖纯虚函数run
   void eat(){cout<<"母亲喜欢吃零食\n";} //覆盖纯虚函数eat
};
class father: public human //派生类father从抽象类human继承
{
   public:
   void run(){cout<<"父亲跑百米要花十秒\n";} //覆盖纯虚函数run
   void eat(){cout<<"父亲不喜欢吃零食\n";} //覆盖纯虚函数eat
};
class uncle:public human //派生类uncle从抽象类human继承
{
   public:
   void run(){cout<<"舅舅跑百米要花十一秒\n";} //覆盖纯虚函数run
   void eat(){cout<<"舅舅喜欢偷吃零食\n";} //覆盖纯虚函数eat
};
int main()
{
   void(human::*pf)()=0; //声明一个成员函数指针pf,该指针属于抽象类human
   human*p=0; //声明一个指向抽象类human的指针p,并将它的内存地址赋为0
   char choice1,choice2; //声明两个字符变量,用来保存两次用户输入的字符
   bool quit=false; //声明一个布尔变量quit作为while循环的条件
   while(quit==false) //当quit为真时退出循环
   {
      cout<<"(0)退出(1)母亲(2)父亲(3)舅舅:"; //选择菜单
      cin>>choice1; //将用户的第1次选择保存在choice1中
      switch(choice1) //将该选择作为判断的依据
      {
         case '0':quit=true;break; //假如输入了字符0,那么将quit的值赋为真,然后退出switch循环
         case '1':p=new mother;break; //假如输入了字符1,那么创建mother类的新对象,并将p指向它,然后退出switch循环
         case '2':p=new father;break; //假如输入了字符2,那么创建father类的新对象,并将p指向它,然后退出switch循环
         case '3':p=new uncle;break; //假如输入了字符3,那么创建uncle类的新对象,并将p指向它,然后退出switch循环
         default:choice1='q';break; //将字符q赋给choice1,然后退出switch循环
      }
   if(quit) //假如quit的值为真
   break; //退出while循环
   if(choice1=='q') //假如choice1的值为字符q
      {cout<<"请输入0到3之间的数字\n";continue;} //输出警告并跳转到while循环的开始处继续执行
   cout<<"(1)跑步(2)进食\n"; //输出选择菜单
   cin>>choice2;   //将第2次用户的选择保存在choice2中
   switch(choice2) //将用户的第2次选择作为判断的依据
   {
      case '1':pf=&human::run;break; //假如输入了字符1,那么将基类human的虚函数run的内存地址赋给成员函数指针,然后退出switch循环。注意,这里的&号是取human类成员函数run的地址
      case '2':pf=&human::eat;break; //假如输入了字符2,那么将基类human的虚函数eat的内存地址赋给成员函数指针,然后退出switch循环
      default:break; //退出switch循环
   }
    (p->*pf)(); //通过指针p来访问对象,通过*pf来访问该对象的成员函数
   delete p; //删除p指针,因为*pf指向的不是对象而是该对象的成员函数,所以没有必要删除pf
   }
   return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值