回调函数实现的实现动态绑定

2019-07-14 09:16发布

  // CallBackApp.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include
using namespace std;
typedef void(*pcb)(char *);   void GetCallBack(pcb callback)
{
    /*do something*/
    char buffer[] = "hello world!";
    callback(buffer);
} void CallbackFun1(char *s)
{
    /* do something */
    cout<     cout<<"call CallbackFun1!"< }  
void CallbackFun2(char *s)
{
    /* do something */
    cout<     cout<<"call CallbackFun2!"< } void CallbackFun3(char *s)
{
    /* do something */
    cout<     cout<<"call CallbackFun3!"< } pcb funArray[3] = {CallbackFun1,CallbackFun2,CallbackFun3}; int _tmain(int argc, _TCHAR* argv[])
{     for(int i=0;i<3;i++)
    {
        GetCallBack(funArray[i]);
    }
   
 return 0;
}                                           #include
#include
using namespace std;
typedef void(*pcb1)(char *);
typedef void(*pcb2)(long value);
typedef void(*pcb3)(string str); struct Funtion
{
 pcb1 f1;
 pcb2 f2;
 pcb3 f3; }myFun; void GetCallBack(Funtion fun)//(pcb1 callback)
{
 /*do something*/
 char buffer[] = "hello world!";
 //callback(buffer);
 fun.f1(buffer);
} void CallbackFun1(char *s)
{
 /* do something */
 cout<  cout<<"call CallbackFun1!"< } void CallbackFun2(char *s)
{
 /* do something */
 cout<  cout<<"call CallbackFun2!"< } void CallbackFun3(char *s)
{
 /* do something */
 cout<  cout<<"call CallbackFun3!"< } pcb1 funArray[3] = {CallbackFun1,CallbackFun2,CallbackFun3};  
int _tmain(int argc, _TCHAR* argv[])
{
 Funtion myFuntion;  for(int i=0;i<3;i++)
 {
  myFuntion.f1 = funArray[i];
  GetCallBack(myFuntion);
 }  return 0;
}