C++ callbacks use the function pointer example

  • 2020-04-02 02:14:33
  • OfStack

C++ callbacks use the function pointer example


#include <iostream>
using namespace std;




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;    
//Register the callback function
void base::registercallback(CALLBACKFUN fun,int k,int j)
{
    pfunc=fun;
    m=k;
    n=j;
}
void base::callcallback()
{
    base::pfunc(m,n);
}

When the lower layer defines the callback function, it needs to provide the following interfaces:

1. Implement the registration interface: provide an interface to the upper layer. Through the interface, the upper layer registers the callback to realize the interface, and the lower layer passes the address of the implementation interface to the defined CALLBACKFUN.

2. Trigger interface: this interface provides trigger behavior, when the interface is called, a function callback will be triggered;


// 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[])
{
    //Registers the lower callback function
    base c_base;
    c_base.registercallback(seiya, 5, 6);
    c_base.callcallback();
    c_base.registercallback(zilong, 7, 8);
    c_base.callcallback();
    return 0;
}


Related articles: