首页 > 编程语言 > 详细

复习 C++ 中类的函数指针

时间:2016-01-16 01:32:15      阅读:140      评论:0      收藏:0      [点我收藏+]

函数指针这种东西,平时工作中基本上不会用到(搬砖的怎么可能用到它呢)。

如果搬砖的在工作中也要接触到函数指针,那就说明一个问题,这套框架不好用,不成熟。

那函数指针会用在哪里咧?你猜咯~~

 

下面是一些基本的用法,根据消息号调到对应的函数:

 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 }

 

如有其他需求,扩展一下就好。。

 

复习 C++ 中类的函数指针

原文:http://www.cnblogs.com/hangj/p/5134842.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!