首先声明,这个是C的用法,C++要杜绝;
函数指针有两种常用的用法:
1.一种是作为结构体成员;
2.函数指针作为函数的参数;
两种方式的意义其它是接口,C 中也叫 回调函数;
函数指针声明:
typedef int (*objFunction_ptr)(int inValue) ;
// 回调函数(函数实现)
- int objFunction(int inValue)
- {
- //你想对参数 进行怎么处理;这个类似接口;也可能是返回的结果;
- int cur= inValue+10;
- return cur;
- }
-
一、函数指针作用结构体成员
// 结构体
- typedef struct FounctionStruct{
- int a;
- objFunction_ptr callback;
- }FOUND_STRUCT;
//结构体传入函数
- int GetMessage(int curValue,FounctionStruct & func)
- {
-
- curValue+= func.a;
- return func.callback(curValue);
- }
// 测试代码
- int main(int argc, char *argv[])
- {
- int curValue = 100;
-
- FounctionStruct func;
- func.a = 20;
- func.callback = &objFunction;
- int tar = GetMessage(curValue,func);
- return 0;
- }
结果 tar =130;
这样就实现了,回调;哪么你可以在回调函数得到,返回的结果,也可以对结果做一些加权了,加密了,一些自己的事情;
二、函数指针作为 函数参数
//函数:
- int GetMessageFun(int curValue,objFunction_ptr callback)
- {
- curValue += 100;
- return callback(curValue);
- }
//调用测试;
- int main(int argc, char *argv[])
- {
- int curValue = 100;
-
- objFunction_ptr fun = & objFunction;
- int tarValue = GetMessageFun(curValue,fun);
- return 0;
- }
结果
tarValue=210;
这样就实现了,回调;哪么你可以在回调函数得到,返回的结果,也可以对结果做一些加权了,加密了,一些自己的事情;