第十七章 特殊成员_成员函数指针数组

//成员函数指针数组
//假如我们将许多成员函数指针放在一个数组中,那么这个数组就叫成员函数指针数组
//该数组中的成员函数指针可以通过数组的下标来进行调用,并且可以用成员函数的内存地址来对数组的各个成员函数指针进行初始化
#include <iostream>
#include <string>
using namespace std;

class Paper
{
public:
	void read(){ cout<<"纸上面的字可以读"<<endl;}
	void write(){ cout<<"纸可以用来写字"<<endl;}
	void burn(){ cout<<"纸可以用来点火"<<endl;}
};
//定义一个Paper类型的函数指针p
typedef void (Paper::*p)();
int main()
{
	//定义了一个p指定的数组func
	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)点火"<<endl;
		 cin>>choice;
		 if(choice[0] < '0' || choice[0] > '3')
		 {
		     cout<<"请输入0到3之间的数值"<<endl;
			 break;
		 }else if(choice[0] == '0')
		 {
		    quit = true;
		 }else
		 {
		    int n;
			pp = new Paper;
			n = atoi(choice);
			(pp->*func[n-1])();
			delete pp;
		 }
	}
    return 0;
}

  

posted @ 2012-09-17 23:58  简单--生活  阅读(472)  评论(0编辑  收藏  举报
简单--生活(CSDN)