C++ 特殊类成员 9-- 9.2 9.3 类的函数指针

#include <iostream>
using namespace std;
/*---------------------------------
     17-09 9.2类的函数指针 9.3类的函数指针
  1) 指向类的成员函数的指针,即类的函数指针
---------------------------------*/
class human
{
public:
virtual void run()=0;
virtual void eat()=0;
};
class mother:public human
{
public:
void run(){cout<<"母亲百米跑需要二十秒"<<endl;}
void eat(){cout<<"母亲喜欢吃零食"<<endl;}
};
class father:public human
{
public:
void run(){cout<<"父亲百米跑需要十五秒"<<endl;}
void eat(){cout<<"父亲不喜欢吃零食"<<endl;}
};
class uncle:public human
{
public:
void run(){cout<<"舅舅百米跑需要十秒"<<endl;}
void eat(){cout<<"舅舅喜欢吃零食"<<endl;}
};
int main()
{
void (human::*pf)()=0;//定义指向纯虚函数的一个函数指针
human *p=0;
char choice1,choice2;
bool quit=false;
while(1)
{
cout<<"0)退出 1)母亲 2)父亲 3)舅舅:";
cin>>choice1;
switch(choice1)
{
case '0':quit=true;break;
case '1':p=new mother;break;
case '2':p=new father;break;
case '3':p=new uncle; break;
default:choice1='q';  break;
}
if(quit)
break;
if(choice1=='q')
{
cout<<"请输入0到3之间的数字:";
continue;
}
cout<<"1)跑步 2)进食:";
cin>>choice2;
switch(choice2)
{
case '1':pf=&human::run;break; //函数指针被赋值
case '2':pf=&human::eat;break;
default:break;
}
(p->*pf)();         //函数指针调用相应函数
delete p;
}

}

运行结果:

0)退出 1)母亲 2)父亲 3)舅舅:1
1)跑步 2)进食:1
母亲百米跑需要二十秒
0)退出 1)母亲 2)父亲 3)舅舅:2
1)跑步 2)进食:2
父亲不喜欢吃零食
0)退出 1)母亲 2)父亲 3)舅舅:3
1)跑步 2)进食:1
舅舅百米跑需要十秒
0)退出 1)母亲 2)父亲 3)舅舅:5
请输入0到3之间的数字:0)退出 1)母亲 2)父亲 3)舅舅:1
1)跑步 2)进食:2
母亲喜欢吃零食
0)退出 1)母亲 2)父亲 3)舅舅:0
Press any key to continue

猜你喜欢

转载自blog.csdn.net/paulliam/article/details/80498423