C++ 特殊类成员 10-- 10成员函数指针数组

#include <iostream>
using namespace std;
/*---------------------------------
     17-10 10成员函数指针数组
---------------------------------*/
class paper
{
public:
void read(){cout<<"纸上的字可以用来读"<<endl;}
void write(){cout<<"纸可以用来写字"<<endl;}
void burn(){cout<<"纸可以用来点火"<<endl;}
};
typedef void (paper::*p)(); //将整个函数指针重命名为p
int main()
{
p func[3]={&paper::read,&paper::write,&paper::burn};//定义函数指针数组并赋初值
paper *pp=0;
char choice[1];
bool quit=false;
while(quit==false)
{
cout<<"0)退出 1)读 2)写 3)点火";
cin>>choice[0];
if(choice[0]>'3'||choice[0]<'0')
{cout<<"请输入0到3之间的数字"<<endl;}
else if(choice[0]=='0')
{quit=true;}
else
{
int n;
pp=new paper;
n =atoi(choice);
(pp->*func[n-1])(); //函数指针数组调用示例
delete pp;
}
}
return 0;

}

运行结果:

0)退出 1)读 2)写 3)点火1
纸上的字可以用来读
0)退出 1)读 2)写 3)点火2
纸可以用来写字
0)退出 1)读 2)写 3)点火3
纸可以用来点火
0)退出 1)读 2)写 3)点火5
请输入0到3之间的数字
0)退出 1)读 2)写 3)点火0
Press any key to continue

猜你喜欢

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