函数指针.回调函数.学习
2010-12-10 17:12
337 查看
最近看Android代码,发现很多回调函数的使用,由于本来对回调函数的不熟悉,感觉很生涩.于是自己写了几行代码来熟悉熟悉.
回调函数首先就得有一个函数指针.
其次,得有供函数指针指向的函数
这里其实最开始遇到了一点问题,呵呵,我最初定义的参数类型为void,因为我希望代码能够更具通用性,但是后来发现,函数指针指向的函数的参数类型必须匹配才行.
函数指针与函数都有了,那么还得有将函数指针与函数联系起来的地方,如果直接在main函数里赋值,感觉太简单了,没有挑战性,于是我再写了一个函数
main函数就很简单了
主要遇到几个问题,一个是函数指针定义的时候参数必须与其欲指向的函数接受的参数类型相同.第二个,typedef的函数指针作为参数传递时,需要传递引用.
回调函数首先就得有一个函数指针.
typedef void (*callback_fun)(char *ptr);
其次,得有供函数指针指向的函数
void output_int(char *x) { cout << "output_int:" << x << endl; }
void output_double(char *y) { cout << "output_double" << y << endl; }
这里其实最开始遇到了一点问题,呵呵,我最初定义的参数类型为void,因为我希望代码能够更具通用性,但是后来发现,函数指针指向的函数的参数类型必须匹配才行.
函数指针与函数都有了,那么还得有将函数指针与函数联系起来的地方,如果直接在main函数里赋值,感觉太简单了,没有挑战性,于是我再写了一个函数
template<typename T> bool QueryCallback(callback_fun &cb,T temp)//这里得注意,回调函数的函数指针必须得传"引用"传地址会报错,而如果作为普通参数传进来,会因为作用域的问题,在函数结束后被销毁.其实这里存有疑惑,为什么不能传指针,难道说typedef的类型,在C++里面只能传引用? { float result = temp - (int)temp; if(result > 0.000001) { cb = output_double; return true; } else if( result < 0.000001 ) { cb = output_int; return true; } else { return false; } }
main函数就很简单了
int main() { char temp[256]; int a = 20; callback_fun cb; if(QueryCallback(cb,a)==false) { return -1; } sprintf(temp,"%d",a); cb(temp); double b = 33.333333; if(QueryCallback(cb,b)==false) { return -1; } sprintf(temp,"%f",b); cb(temp); return 0; }
主要遇到几个问题,一个是函数指针定义的时候参数必须与其欲指向的函数接受的参数类型相同.第二个,typedef的函数指针作为参数传递时,需要传递引用.
相关文章推荐
- 学习回调函数同时引申出用函数参数返回一些值或指针
- [学习记录]Objective-C回调函数(函数指针)
- C语言学习笔记 lesson15&16 函数2指针的偏移
- 函数指针与回调函数
- 学习函数指针
- delphi 中的函数指针 回调函数(传递函数指针,以及它需要的函数参数)
- Go语言学习六:指针与传递到函数的指针
- 回调函数,监听函数 关系 个人学习理解
- c语言学习,指针函数、函数指针、指针的指针、指向指针数组的指针
- [C++学习笔记14]动态创建对象(定义静态方法实现在map查找具体类名对应的创建函数,并返回函数指针,map真是一个万能类)good
- PHP学习笔记——使用回调函数处理数组函数array_map()
- C++学习笔记九之函数指针
- iOS开发学习之C语言---C10 函数指针-2
- 指针,函数,数组打杂混学习以及typedef学习笔记
- 回调函数与函数指针
- 函数类型和函数指针类型(摘自 linux c编程一站式学习)
- FreeBASIC学习笔记——8.4 指针与函数/过程
- 指向函数的指针(pointers to functions)和回调函数
- C函数指针应用之回调函数
- C++学习笔记18——指向函数的指针