函数指针数组用于同种数据结构,多种处理类型的应用中,主要好处是避免了判断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);}