// cmdmap.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <map> using namespace std; class CTest; typedef int (CTest::*Action)(char*); map<unsigned int , Action> cmdMap; struct CmdStruct { unsigned int cmdCode; //命令码 int dummy;//其它参数 }; class CTest { public: CTest(){} ~CTest(){} int proc_msg_1( char* ) { printf("proc msg 1/n"); return 0; } int proc_msg_2( char* ) { printf("proc msg 2/n"); return 0; } void proc_cmd( char* pCmd ) { unsigned int cmd = ((CmdStruct*)(void*)pCmd)->cmdCode; //查找命令 map<unsigned int, Action>::iterator it = cmdMap.find( cmd ); //未找到命令 if ( it == cmdMap.end() ) { printf( "unknown cmd: %u/n", cmd ); return ; } Action act = it->second; (this->*act)( pCmd ); } }; int main(int argc, char* argv[]) { //初始化命令 cmdMap.insert( make_pair(1, &CTest::proc_msg_1 )); cmdMap.insert( make_pair(2, &CTest::proc_msg_2 )); CTest test; CmdStruct cmd; //处理命令 cmd.cmdCode = 2; test.proc_cmd( (char*)&cmd ); cmd.cmdCode = 1; test.proc_cmd( (char*)&cmd ); cmd.cmdCode = 3; test.proc_cmd( (char*)&cmd ); system( "pause" ); return 0; }