c++回调之利用函数指针示例
复制代码 代码如下:
#include <iostream>using namespace std; /************************************************************************//* 下层实现: CALLBACK *//************************************************************************/typedef void (*CALLBACKFUN)(int a,int b);
class base
{private: int m; int n; static CALLBACKFUN pfunc;public: base():m(0), n(0){}; void registercallback(CALLBACKFUN fun,int k,int j); void callcallback();};CALLBACKFUN base::pfunc=NULL; /* static初始化 */
// 注册回调函数
void base::registercallback(CALLBACKFUN fun,int k,int j){ pfunc=fun; m=k; n=j;}void base::callcallback()
{ base::pfunc(m,n);}下层定义回调函数的时候,需要提供以下几个接口:
1. 实现注册接口:提供一个接口给上层,通过该接口,上层注册回调实现接口,下层将该实现接口地址传递给定义的回调指针(CALLBACKFUN),该初始化动作是必须的,否则无法实现回调;
2. 触发接口:该接口提供触发行为,当调用该接口时,就会触发一次函数回调;
复制代码 代码如下:
// cbByfunction.cpp : Defines the entry point for the console application.//#include "stdafx.h"
#include "cbByfunction.h"/************************************************************************/
/* 上层回调注册 *//************************************************************************/void seiya(int a,int b){ cout << "..." << a << "..." << 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;}int main(int argc, char* argv[])
{ // 注册下层回调函数 base c_base; c_base.registercallback(seiya, 5, 6); c_base.callcallback(); c_base.registercallback(zilong, 7, 8); c_base.callcallback(); return 0;}
精彩评论