Be aware of the difference between the member functions of Class C + + and the general C function. The C + + class takes the This rule transfer function. In using the member function of a class as a callback function, the member function is required to be known as a static member function, and notice that the parameter passing rules are declared when the function is famous.
A simple example:
CallBackClass.h
#ifndef CALL_BACK_CLASS_H#define CALL_BACK_CLASS_Hclass CallBack{public: CallBack(){} ~CallBack(){} void(*call_back_func)(int);//先声明函数指针,即我们要调用的函数public: /*安装函数指针*/ voidcall_backvoid(*call_back_func)(int),int n ){ call_back_func(n); }};#endif
Here the declaration and definition are written together for convenience.
Main.cpp
#include <iostream>#include "CallBackClass.h"usingnamespacestd;void func(int n){ //该函数需为全局,或类中的静态函数 cout<<n<<endl;}int main(){ CallBack a; a.call_back_func(func,10);}
We call the member function of object a call_back_func, the function parameter is a function pointer and an integral type. The passed-in function name is passed in to the address, making it call the Func function.
CallBackTest.h
#ifndef Call_back_test_h#define call_back_test_hClass callbacktest{ Public:callbacktest(){}; ~callbacktest () {}; typedefvoid(*call_back_func) (void*,int); Public:/* Bind Object */void Call_back(void* Pthisobject,void(*call_back_func) (void*,int),intN) {my_object = Pthisobject; My_func = Call_back_func; My_n = n; }voidExec_back_func () {my_func (my_object,my_n);//This will bind to our static function}Private: Call_back_func My_func;intMy_n;void* MY_OBJECT;};#endif
Main.cpp
#include <iostream>#include "CallBackTest.h"using namespace STD;classproxy{ Public:Static voidNeed_call_func (void* Pcurobject,intN) {proxy* pobject = (proxy*) pcurobject; Pobject->execfunc (n); }voidExec () {Callbacktest callback; Callback.call_back ( This, Need_call_func,Ten); Callback.enec_back_func (); }voidExecfunc (intN) {cout<<n<<endl; }};intMain () {Proxy test; Test. Exec ();return 0;}
As we all know, the static function of a class is shared by instances of that class.
The point here is that static functions are installed.
1, Callback.call_back (this,need_call_func,10); Confirm the parameters of an object
2, Callback.exec_back_func (); Install our parameters to the static function
3. Execute static function contents.
In fact, the description is not very good, please try their own understanding.
It is not clear that the program can be debugged to understand the execution of the program.
C + + Writes the callback function in the class