成员函数指针表

函数指针和成员函数指针的一个公共用途是,将它们存储在函数表中。函数表是函数指针的集合,在运行时从中选择给定调用。

对具有几个相同类型成员的类而言,可以使用这样的表来从这些成员的集合中选择一个。假定扩展screen类以包含几个成员函数,其中每一个在特定方向移动光标:

class Screen
{
public:
	//other interface and implementation members as before
	//same type of functions for cursor movement, can be integrated into member function pointer array.
	Screen &   home();
	Screen &	 forward();
	Screen &  back();
	Screen &  up();
	Screen & down();
};

我们可能希望定义一个move函数,它可以调用这些函数中的任意一个并执行指定的动作,为此,在Screen中增加一个static成员,该成员是光标移动函数的指针的数组。
class Screen
{
	//Action is pointer that can be assigned any of the cursor movement members
	typedef Screen & ( Screen:: * Action )  ();
	//function table
	static Action menu[];

	//specify which direction to move
	enum Directions { HOME, FORWORD, BACK, UP, DOWN };
	Screen & move ( Directions );
};

名为menu的数组将保存指向每个光标移动函数的指针,将在对应于Direction中枚举成员的偏移位置保存那些函数,move函数接受枚举成员并调用适当函数:

Screen & Screen::move( Directions cm )
{
	//fetch the element in Menu indexed by cm
	//run that member on behalf of this object
	( this->*menu[cm])();
	return *this;
}

调用move时,传给它一个枚举成员,指出向哪个方向移动光标:

	Screen myScreen;
	myScreen.move(Screen::HOME);
	myScreen.move(Screen::BACK);

剩下的是定义和初始化表本身:

Screen ::Action Screen ::menu [] =
{
	&Screen::home,
	&Screen::forward,
	&Screen::back,
	&Screen::up;
	&Screen::down
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值