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\n");  
  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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM