成员函数指针数组,处理函数中调用:

来源:互联网 发布:在线英语培训软件 编辑:程序博客网 时间:2024/06/09 14:35

成员函数指针数组

分类: c++语言 341人阅读 评论(0) 收藏 举报

函数指针数组用于同种数据结构,多种处理类型的应用中,主要好处是避免了判断switch的使用。

普通函数作为函数指针数组元素可简单赋值,而类的成员函数作为函数指针数组的元素,要特别注意声明的时候(如typedef)要指定类作用域,否则编译会出错。

例子:
/////////////////////// a.h

class A
{
public:
 A();
 void dispatchMsg(uint32 cmd,void* content, uint32 contentLength);
private:
 Bool onMsg1(ibuffer &buffer);
 Bool onMsg2(ibuffer &inbuf);
 Bool onMsg3(ibuffer &inbuf);
private:
 typedef Bool (A::*CMDFUN)(ibuffer &buffer); // 注意指定类作用域A::
 CMDFUN m_cmdFun[FUN_MAX];
}
/////////////////////// a.cpp
构造函数里赋值:
A::A()
{
 m_cmdFun[PET_PASSIVEMODE]  = onPetPassiveMode;
 m_cmdFun[PET_SETSKILLAUTOCAST]  = onPetSkillSlotCheck;
 m_cmdFun[PET_MOVESKILL]   = onPetMoveSkill;
}
处理函数中调用:
void A:dispatchMsg(uint32 cmd,void* content, uint32 contentLength)
{
 // ...
 inbuf = getBuff(content,contentLength);
 (this->*m_cmdFun[cmd])(inbuf);

原创粉丝点击