函数指针数组的点滴

以下内容摘至《C++编程思想》:

#include   <iostream>
using   namespace   std;

#define   DF(N)   void   N(){cout < < "function   "#N "   called " < <endl;}  
DF(a);DF(b);DF(c);DF(d);

void   (*func_table[])()={a,b,c,d};

int   main()
{
    while(1){
    cout < < "press   a   key   from 'a 'to   'd '   or   q   to   quit " < <endl;
    char   c;

    cin> > c;

    if(c== 'q ')
        break;
    if(c < 'a '||c> 'd ')
        continue;
    (*func_table[c- 'a '])();
    }
    return   0   ;
}

可以理解为:

DF(a);DF(b);DF(c);DF(d);//申明并定义了a(),b(),c(),d()四个不带返回直不带参数的函数
可扩展成:
void a(){cout < < "function a called " < <endl;}
void b(){cout < < "function b called " < <endl;}
void c(){cout < < "function c called " < <endl;}
void d(){cout < < "function d called " < <endl;}


void (*func_table[])()={a,b,c,d};//函数指针数组的形式
扩展成
func_table[0] = a;
func_table[1] = b;
func_table[2] = c;
func_table[3] = d;

于是*func_table[c- 'a ']就掉用了a(),b(),c(),d()中的一个,因此,输出结果因该是
function a called  
function b called  
function c called  
function d called
中的一个

 

利用函数指针数组写个很简单消息映射机制:
enum msg_cmd_t {
 msg_cmd_start = 0,
 
 msg_player_login = 1,
 
 //...,other msg
 
 msg_cmd_end = 1000,
 msg_cmd_max
};

//函数指针数组

int (*msg_hdlr_t[msg_cmd_max])(player* p, void* msg_body, int msg_len) = {0};

//注册机制

#define SET_MSG_HANDLE(op_) /
 do { /
  if ( msg_hdlr_t[msg_ ## op_] != 0 ) { /
   ERROR_LOG("error cmd=%u", msg_ ## op_); /
   return false; /
  } /
  msg_hdlr_t[msg_ ## op_] = op_ ## _cmd; /
 } while (0)
 

注册消息:
SET_MSG_HANDLE(player_login);

int player_login_cmd(player* p, void* msg_body, int msg_len)
{
 //TODO:
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值