Example of a C + + callback using function pointers
Copy Code code as follows:
#include <iostream>
using namespace Std;
/************************************************************************/
/* LOWER implementation: 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::p func=null; /* Static Initialization * *
Registering callback Functions
void Base::registercallback (Callbackfun fun,int k,int J)
{
Pfunc=fun;
M=k;
N=j;
}
void Base::callcallback ()
{
Base::p func (M,n);
}
The following interfaces are required when defining callback functions at the lower level:
1. Implementation Registration interface: Provide an interface to the upper level, through the interface, the upper register callback implementation interface, the lower level of the implementation of the interface address to the definition of the callback pointer (Callbackfun), the initialization of the action is necessary, otherwise can not achieve callback;
2. Trigger interface: This interface provides triggering behavior, when the interface is invoked, a function callback is triggered;
Copy Code code as follows:
CbByfunction.cpp:Defines the entry point for the console application.
//
#include "stdafx.h"
#include "CbByfunction.h"
/************************************************************************/
/* Upper CALLBACK registration * *
/************************************************************************/
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[])
{
Registering downlevel callback functions
Base c_base;
C_base.registercallback (Seiya, 5, 6);
C_base.callcallback ();
C_base.registercallback (Zilong, 7, 8);
C_base.callcallback ();
return 0;
}