1、在类User中触发,然后在Call类中执行相关函数
#include <iostream> using namespace std; typedef void (*CALLBACK)(int a,int b);
class Call { public: static void seiya(int a,int b) //为了和User CALLBACK关联,这里必须声明为静态 { cout<<a<<endl<<b<<endl; cout<<"this is seiya callback function"<<endl; }; static void zilong(int a,int b)//为了和User CALLBACK关联,这里必须声明为静态 { cout<<a<<endl<<b<<endl; cout<<"this is zilong callback function"<<endl; }; }; class User { private: int m; int n; static CALLBACK func;//必须声明为静态 public: void register_callback(CALLBACK fun,int k,int j); void call_callback(); };
CALLBACK User::func=NULL;
void User::register_callback(CALLBACK fun,int k,int j) { func=fun; m=k; n=j; }
void User::call_callback() { User::func(m,n); }
int main( ) { User user; user.register_callback(Call::seiya,2,3); user.call_callback();//2 3 this is seiya callback function user.register_callback(Call::zilong,5,6); user.call_callback();//5 6 this is zilong callback function while(1); return 0 ; } // 注意事项: // 回调函数是在类User中触发,然后在Call类中执行相关函数。 // Call类中的CALLBACK seiya函数必须为静态 // User类中的函数指针static CALLBACK func必须为静态。
链接:
1、回调函数的 C + + 封装 刘书良 , 韩 力 , 罗辞勇 (重庆大学 电气工程学院 ,重庆 400044)
http://read.pudn.com/downloads111/ebook/461115/%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0%E7%9A%84C%20%2B%2B%20%E5%B0%81%E8%A3%85.pdf
2、C/C++之回调函数 (基础:函数指针 函数指针数组 回调函数)http://www.cnblogs.com/chenyuming507950417/archive/2012/01/02/2310114.html
3、C++回调机制实现 http://www.cnblogs.com/dankye/archive/2012/08/25/2655816.html
class CCallback { public: void Func(int a) { cout<<"CCallback member function callback called with para="<<a<<endl; } }; class CCallback2 { public: void Func(int a) { cout<<"CCallback2 member function callback called with para="<<a<<endl; } }; // typedef void (CCallback::*pMemberFunc)(int); // void Caller(CCallback* pObj,pMemberFunc p) // { // (pObj->*p)(1); // } // 上面这种方法,dll还需要和用户使用共同的类定义CCallback。 // 进化:如下,使用模板,这样dll中的Caller根本不必知道类CCallback2是如何定义的。 template<typename T ,typename IN1_T > void Caller(T* pObj,void (T::*p)(IN1_T)) { (pObj->*p)(1); } int main(int argc, char* argv[]) { CCallback obj; Caller(&obj,&CCallback::Func); CCallback2 obj2; Caller(&obj2,&CCallback2::Func); system("pause"); return 0 ; }