回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。
⑴定义一个回调函数;
⑵提供函数实现的一方在初始化的时候,将回调函数的函数
指针注册给调用者;
⑶当特定的事件或条件发生的时候,调用者使用
函数指针调用回调函数对事件进行处理。
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
typedef void(_stdcall *MyFun)(int n, string str);
class Call
{
private:
MyFun myFun;
public:
void SetFun(MyFun _myFun)
{
myFun = _myFun;
}
void LetRun(int n, string str)
{
myFun(n, str);
}
};
void _stdcall Test(int n, string str) //如果不定义全局变量,而定义在类中 则必须是 静态成员函数
{
while (n-->0)
cout << n << " " << str << endl;
}
int main(int argc, char* argv[])
{
Call call;
call.SetFun((MyFun)Test); //调回调函数的接口,并传入一个函数作为参数
call.LetRun(10, "hello");
printf("Hello World!\n");
return 0;
}