C++ 回调函数 --函数的接口 讲解
[cpp]view plaincopy
如果参数是一个函数指针,调用者可以传递一个函数的地址给实现者,让实现者去调用它,这称为回调函数(CallbackFunction)。例如qsort(3)和bsearch(3)。
表24.7.回调函数示例:voidfunc(void(*f)(void*),void*p);
调用者实现者
1.提供一个回调函数,再提供一个准备传给回调函数的参数。
2.把回调函数传给参数f,把准备传给回调函数的参数按void*类型传给参数p
1.在适当的时候根据调用者传来的函数指针f调用回调函数,将调用者传来的参数p转交给回调函数,即调用f(p);
以下是一个简单的例子。实现了一个repeat_three_times函数,可以把调用者传来的任何回调函数连续执行三次。
例24.7.回调函数
/*para_callback.h*/
#ifndefPARA_CALLBACK_H
#definePARA_CALLBACK_H
typedefvoid(*callback_t)(void*);
externvoidrepeat_three_times(callback_t,void*);
#endif
/*para_callback.c*/
#include"para_callback.h"
voidrepeat_three_times(callback_tf,void*para)
{
f(para);
f(para);
f(para);
}
/*main.c*/
#include<stdio.h>
#include"para_callback.h"
voidsay_hello(void*str)
{
printf("Hello%s\n",(constchar*)str);
}
voidcount_numbers(void*num)
{
inti;
for(i=1;i<=(int)num;i++)
printf("%d",i);
putchar("\n");
}
intmain(void)
{
repeat_three_times(say_hello,"Guys");
repeat_three_times(count_numbers,(void*)4);
return0;
}