^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
date: 20180811
回調函數:就是一個通過函數指針調用的函數。如果你把函數的指針作為參數傳遞給另外一個函數,檔這個指針被用來調用其指向的函數時,我們就說這是回調函數。回調函數不是由該函數的實現方直接調用,而是在特定的事件或條件發生時由另外的一個調用,用於對該事件或條件進行的響應。
函數指針:
返回值 (*函數名)(參數列表);
如:int (*callback)(int i);
1. typedef定義函數指針類型
#include <iostream> using namespace std; typedef int (*fp)(char c); int f0 (char c) { cout << "f0, c= " << c << endl; return 0; }; int f1 (char c) { cout << "f1, c= " << c << endl; return -1; }; int main () { fp Fp; Fp = f0; cout << Fp ('a') << endl; system ("pause"); Fp = f1; cout << Fp ('b') << endl; system ("pause"); return 0; }
輸出:
2. typedef定義函數類型
#include <iostream> using namespace std; typedef int f(char c); int f0 (char c) { cout << "f0, c= " << c << endl; return 0; }; int f1 (char c) { cout << "f1, c= " << c << endl; return -1; }; int main () { f *Fp; Fp = f0; cout << Fp ('a') << endl; system ("pause"); Fp = f1; cout << Fp ('b') << endl; system ("pause"); return 0; }
輸出:
——————————————————————
回調函數有什么作用呢?
1. 回調函數就是由用戶自己做主的函數:
比如,OnTimer()定時器的回調函數,當時間到了需要做什么完全交給用戶自己處理。
2. 回調函數很有可能是輸入輸出的一種方式:
對於DLL來說,函數的參數由輸入參數,輸出參數。回調函數的指針作為其參數的話,可以起到輸入的作用。當然,也可以起到輸出的作用。
通過回調函數,可以一次又一次頻繁的傳遞值——比如視頻流。
3. 回調函數里面的實現,仍然可以是回調函數。
總之,回調函數的作用:
>. 決定權交給客戶端
>. 與客戶端進行交流
>. 通過客戶端進行輸入
>. 通過客戶端進行輸出
實例:
#include <iostream> using namespace std; typedef int (*CallbackFun)( char *p_ch ); int AFun (char *p_ch) { cout << "Afun 回調:\t" << p_ch << endl; return 0; } int BFun (char *p_ch) { cout << "BFun 回調:\t" << p_ch << endl; return 0; } int Call (CallbackFun p_Callback, char *p_ch) { cout << "call 直接打印出字符:\t" << p_ch << endl; p_Callback (p_ch); return 0; } int Call2 (char *p_ch, int (*pfun)(char *)) { cout << "通過指針方式執行回調函數。。。" << endl; ( *pfun )( p_ch ); return 0; } int Call3 (char *p_ch, CallbackFun p_Callback) { cout << "通過命名方式執行回調函數。。。" << endl; p_Callback (p_ch); return 0; } int main () { char *p_ch = "Hello world!"; Call (AFun, p_ch); Call (BFun, p_ch); Call2 (p_ch, AFun); Call3 (p_ch, AFun); system ("pause"); return 0; }
輸出:
——————————————————————