窗口回调函数,定时器回调函数,都属于回调函数。一般来讲:回调函数都是基于某种消息驱动,在获取相应消息时调用该函数。回调函数分系统回调和用户回调。
回调函数是由用户撰写,而由操作系统调用的一类函数,回调函数可以把调用者和被调用者分开,调用者(例如操作系统)不需要关心被调用者到底是哪个函数,它所知道的就是有这么一类函数,这类满足相同的函数签名(函数原型,参数,返回值等),由用户书写完毕后在被调用就可以了。
实现上回调函数一般都是通过函数指针来实现的。
典型的回调函数是MFC 下的定时器处理函数ontimer,你只需要添加这个消息响应函数,然后在初始化的时候将ontimer指针传递给操作系统,操作系统就会按照设定好的时间来循环调用ontimer函数了、你甚至可以将main函数理解成回调函数,因为它不会被客户程序员调用,只会被客户程序员撰写,然后由操作系统来调用。类似的函数 SDK下的窗口过程函数,也是回调函数。
#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.registercallback(seiya,2,3);
ba.callcallback();
ba.registercallback(zilong,5,6);
ba.callcallback();
}