C++ 使用回调函数的方式 和 作用。 持续更新

先看两个demo:

一.在类test1中调用函数print() ,把print()的函数指针传递给test1的函数指针参数

test1.h:

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5. typedef void (*FUNP)();  
  6. class test1  
  7. {  
  8. public:  
  9.     void fun1(FUNP p)  
  10.     {  
  11.         (*p)();  
  12.     }  
  13. };  


main.cpp

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include "test1.h"  
  3.   
  4. void print();  
  5.   
  6. int main()  
  7. {  
  8.     test1 tet1;  
  9.     tet1.fun1(print);  
  10.     getchar();  
  11.     return 0;  
  12. }  
  13.   
  14. // void (*p)()  
  15. void print()  
  16. {  
  17.     printf("hello world ");  
  18. }  

// 打印 “hello world”

二.类Test1 中调用Test2的方法函数。  在类test2中包含test1对象,将test2中的函数指针传给test1

test2.h:

#include "test1.h"

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class Test2  
  5. {  
  6. public:  
  7.     Test2()  
  8.     {  
  9.         tet1.fun1(fun2);  
  10.     }  
  11.     static void fun2()  
  12.     {  
  13.         cout<<"Test2"<<endl;  
  14.     }  
  15. public:  
  16.     test1 tet1;  
  17. };  

test1.h:

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5. typedef void (*FUNP)();  
  6. class test1  
  7. {  
  8. public:  
  9.     void fun1(FUNP p)  
  10.     {  
  11.         (*p)();  
  12.     }  
  13. };  

main:

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include "test2.h"  
  3. int main()  
  4. {  
  5.     Test2 tet2;   
  6.     getchar();  
  7.     return 0;  
  8. }  


// 结果:打印“Test2”

附上两个deome,搞清楚的话 回调函数基本可以套着用了

http://download.csdn.net/my

http://blog.csdn.net/qq_17242957/article/details/53002652

原文地址:https://www.cnblogs.com/findumars/p/6034682.html