复习 C++ 中类的函数指针
函数指针这种东西,平时工作中基本上不会用到。
那函数指针会用在哪里?
下面是一些基本的用法,根据消息号调到对应的函数:
1 #include <iostream> 2 #include <map> 3 4 enum MsgCode 5 { 6 MSGCODE1 = 1, 7 MSGCODE2 = 2, 8 }; 9 10 class Fuck 11 { 12 public: 13 Fuck(int i=0):f(i){ 14 // register functions 15 mapFunction[MSGCODE1] = &Fuck::method1; 16 mapFunction[MSGCODE2] = &Fuck::method2; 17 // ... 18 } 19 20 public: 21 int method1(int i); 22 int method2(int i); 23 // ... 24 25 public: 26 bool processMsg(int msg_code, int msg_data); 27 28 private: 29 int f; 30 31 private: 32 std::map<int, int (Fuck::*)(int i)> mapFunction; 33 // int (Fuck::*mapFunction[1024])(int i); 34 // std::map<std::string, int (Fuck::*)(int i)> mapFunction; 35 }; 36 37 int Fuck::method1(int i) 38 { 39 return i * f; 40 } 41 42 int Fuck::method2(int i) 43 { 44 return i * f + 1; 45 } 46 47 bool Fuck::processMsg(int msg_code, int msg_data) 48 { 49 std::map<int, int (Fuck::*)(int i)>::iterator it = mapFunction.find(msg_code); 50 if(it == mapFunction.end()) 51 return 0; 52 53 int result = (this->*it->second)(msg_data); 54 std::cout << result << std::endl; 55 56 return 1; 57 } 58 59 int main(int argc, char** argv) 60 { 61 Fuck fuck(1); 62 63 int msg_code = MSGCODE1; 64 int msg_data = 1; 65 fuck.processMsg(msg_code, msg_data); 66 67 msg_code = MSGCODE2; 68 msg_data = 1; 69 fuck.processMsg(msg_code, msg_data); 70 71 return 0; 72 }
如有其他需求,扩展一下就好。。
+V why_null 请备注:from博客园