分享

C++ 回调函数 --函数的接口 讲解

 wusiqi111 2017-05-18


  1.    
  2. 如果参数是一个函数指针,调用者可以传递一个函数的地址给实现者,让实现者去调用它,这称为回调函数(Callback Function)。例如qsort(3)和bsearch(3)。  
  3. 表 24.7. 回调函数示例:void func(void (*f)(void *), void *p);  
  4. 调用者实现者  
  5.   
  6.  1. 提供一个回调函数,再提供一个准备传给回调函数的参数。  
  7.   
  8.  2. 把回调函数传给参数f,把准备传给回调函数的参数按void *类型传给参数p  
  9.   
  10.    
  11.   
  12.  1. 在适当的时候根据调用者传来的函数指针f调用回调函数,将调用者传来的参数p转交给回调函数,即调用f(p);  
  13.   
  14.    
  15.   
  16. 以下是一个简单的例子。实现了一个repeat_three_times函数,可以把调用者传来的任何回调函数连续执行三次。  
  17. 例 24.7. 回调函数  
  18. /* para_callback.h */  
  19. #ifndef PARA_CALLBACK_H  
  20. #define PARA_CALLBACK_H  
  21.   
  22. typedef void (*callback_t)(void *);  
  23. extern void repeat_three_times(callback_t, void *);  
  24.   
  25. #endif  
  26. /* para_callback.c */  
  27. #include "para_callback.h"  
  28.   
  29. void repeat_three_times(callback_t f, void *para)  
  30. {  
  31.      f(para);  
  32.      f(para);  
  33.      f(para);  
  34. }  
  35. /* main.c */  
  36. #include <stdio.h>  
  37. #include "para_callback.h"  
  38.   
  39. void say_hello(void *str)  
  40. {  
  41.      printf("Hello %s\n", (const char *)str);  
  42. }  
  43.   
  44. void count_numbers(void *num)  
  45. {  
  46.      int i;  
  47.      for(i=1; i<=(int)num; i++)  
  48.           printf("%d ", i);  
  49.      putchar('\n');  
  50. }  
  51.   
  52. int main(void)  
  53. {  
  54.      repeat_three_times(say_hello, "Guys");  
  55.      repeat_three_times(count_numbers, (void *)4);  
  56.      return 0;  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多