成员函数指针表

来源:互联网 发布:linux如何清理根目录 编辑:程序博客网 时间:2024/04/28 10:05

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

对具有几个相同类型成员的类而言,可以使用这样的表来从这些成员的集合中选择一个。假定扩展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 memberstypedef Screen & ( Screen:: * Action )  ();//function tablestatic Action menu[];//specify which direction to moveenum 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};


原创粉丝点击