zoukankan      html  css  js  c++  java
  • 复习 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 }

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

  • 相关阅读:
    栏目调用 sql语句
    一场豪赌 微软的未来取决于Windows 8
    mark
    [导入].net中的如何私有部署强命名组件
    q160问题,www.q160.com,ie被篡改
    解决jdgui保存源码自动添加注释的情况
    汉诺塔问题
    软件测试 方法总结
    javascript 基础篇4 window对象,DOM
    javascript 进阶篇1 正则表达式,cookie管理,userData
  • 原文地址:https://www.cnblogs.com/hangj/p/5134842.html
Copyright © 2011-2022 走看看