函数指针高级运用(C函数指针)

来源:互联网 发布:windows 10 蓝牙丢失 编辑:程序博客网 时间:2024/05/21 15:47


阅读本文先阅读下两文:


          http://blog.csdn.net/gubenpeiyuan/article/details/11193865

          http://blog.csdn.net/gubenpeiyuan/article/details/11192583


阅读之后,给出一个函数运用实例。方式为定义一个函数指针类型,直接调用后,回调。


typedef void (*CallFun)(Msg *msg);bool CheckConfigAndDoFun(const char *ConfigPath,const char *ConfigName,const char *Val, CallFun fun,Msg *msg){char *ConfigVal = GetConfigVal(ConfigPath,ConfigName);if(ConfigVal==NULL){printf("Val Get Error\n");return 1 ;}else{if(!strcmp(ConfigVal,Val)){(*fun)(msg);return 0 ;}else{printf("Val Not match\n");return 1 ;}}return 1 ;}


CheckConfigAndDoFun("TrackConfig","DataLogEnable","Yes",&PublishRecordContentToTXT,&msgInstance);


注:C++若是调用类中的成员,编译时需加入 -fpermissive

         或者将被引用的函数放到类的外部。


更易用的一种,使用数组来存储函数指针,更方便使用:


#include <stdio.h>typedef int (*fun_t)(int , int);/*构造一个枚举值对应的操作符标示(ID)*/ enum{OPER_ADD = 0,OPER_SUB,OPER_MUL,OPER_DIV,OPER_NUM//操作符个数 };int add(int a,int b){return (a + b);}int sub(int a,int b){return (a - b);}int mul(int a,int b){return (a * b);}int div(int a,int b){return (int)(a / b);}static const fun_t oper_table[OPER_NUM] = {add,sub,mul,div};int main(int argc ,char **argv){int a , b , result;a = 100;b = 20;/* use table operation : Add */result = oper_table[OPER_ADD](a,b);printf("Table operation : %d + %d = %d\n" , a , b , result);/* use table operation : Sub */result = oper_table[OPER_SUB](a,b);printf("Table operation : %d + %d = %d\n" , a , b , result);/* use table operation : Multiply */result = oper_table[OPER_MUL](a,b);printf("Table operation : %d + %d = %d\n" , a , b , result);/* use table operation : Divide */result = oper_table[OPER_DIV](a,b);printf("Table operation : %d + %d = %d\n" , a , b , result);return 0;}






原创粉丝点击