您的位置:首页 > 编程语言 > C语言/C++

C++ 回调函数的简单例子(转)

2016-09-22 10:12 183 查看
原文转自 http://blog.csdn.net/wnlwcg/article/details/6930990#

1、调用端

// 下面的这个_stdcall很重要的
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;
}


2、被调用端

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);
}
};


3、回调过程:调用回调接口【SetFun】,并设置回调接受函数【Test】 -----> 保存 被调用端传来的 参数 【myFun】-----> 等待.....----->

LetRun ----->myFun------>回调到Test
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: