回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用为调用它所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。
回调函数实现的机制是
⑴定义一个回调函数;
⑵提供函数实现的一方在初始化的时候,将回调函数的函数指针注册给调用者;
⑶当特定的事件或条件发生的时候,调用者使用函数指针调用回调函数对事件进行处理。
实例代码:
#include <iostream>
using namespace std;
typedef void (*CALLBACK)(int a,int b);
class base
{
private:
int m;
int n;
static CALLBACK func;
public:
void registercallback(CALLBACK fun,int k,int j);
void callcallback();
};
CALLBACK base::func=NULL;
void base::registercallback(CALLBACK fun,int k,int j)
{
func=fun;
m=k;
n=j;
}
void base::callcallback()
{
base::func(m,n);
}
void seiya(int a,int b)
{
cout<<a<<endl<<b<<endl;
cout<<"this is seiya callback function"<<endl;
}
void zilong(int a,int b)
{
cout<<a<<endl<<b<<endl;
cout<<"this is zilong callback function"<<endl;
}
void main(void)
{
base ba;
ba.reg