为了弄明白这种函数的奥妙,首先提出三个问题:
1. 回调函数是什么东西?
2. 回调函数怎么开发,怎么使用?
3. 回调函数的作用,应该在什么情况下使用?
看了这么多的资料,一句话:回调函数就是函数指针的一种用法。
#include <stdio.h>
void printWelcome(int len)
{
printf("欢迎欢迎 -- %d\n", len);
}
void printGoodbye(int len)
{
printf("送客送客 -- %d\n", len);
}
void callback(int times, void (* print)(int))
{ int i;
for (i = 0; i < times; ++i)
{
print(i);
}
printf("\n我不知道你是迎客还是送客!\n\n");
}
void main(void)
{
callback(10, printWelcome);
callback(10, printGoodbye);
printWelcome(5);
}
结果:
欢迎欢迎 -- 0
欢迎欢迎 -- 1
欢迎欢迎 -- 2
欢迎欢迎 -- 3
欢迎欢迎 -- 4
欢迎欢迎 -- 5
欢迎欢迎 -- 6
欢迎欢迎 -- 7
欢迎欢迎 -- 8
欢迎欢迎 -- 9
我不知道你是迎客还是送客!
送客送客 -- 0
送客送客 -- 1
送客送客 -- 2
送客送客 -- 3
送客送客 -- 4
送客送客 -- 5
送客送客 -- 6
送客送客 -- 7
送客送客 -- 8
送客送客 -- 9
我不知道你是迎客还是送客!
欢迎欢迎 -- 5
有一位朋友用分层的概念来解释了回调机制:
callback函数为B层
main函数和print*函数为A层
A层调用了B层的回调函数callmeback,而B层的回调函数调用了A层的实现函数print*
说白了B层就是一个接口。