#includevoidprogramA_FunA1(){printf("I'am ProgramA_FunA1 and be called..\n");}voidprogramA_FunA2(){printf("I'am ProgramA_FunA2 and be called..\n");}voidprogramB_FunB1(void(*callback)()){printf("I'am programB_FunB1 and be called..\n");callback(); }intmain(int argc,char**argv){programA_FunA1();programB_FunB1(programA_FunA2); }
执行结果:
没有什么可说的,非常简单。
2.2 类的静态函数作为回调函数
#includeclassProgramA{public:voidFunA1(){printf("I'am ProgramA.FunA1() and be called..\n");}staticvoidFunA2(){printf("I'am ProgramA.FunA2() and be called..\n");} };classProgramB{public:voidFunB1(void(*callback)()){printf("I'am ProgramB.FunB1() and be called..\n");callback();} };intmain(int argc,char**argv){ProgramA PA;PA.FunA1();ProgramB PB;PB.FunB1(ProgramA::FunA2); }
#includeclassProgramA{public:voidFunA1(){printf("I'am ProgramA.FunA1() and be called..\n");}voidFunA2(){printf("I'am ProgramA.FunA2() and be called..\n");} };classProgramB{public:voidFunB1(void(ProgramA::*callback)(),void*context){printf("I'am ProgramB.FunB1() and be called..\n");((ProgramA *)context->*callback)();} };intmain(int argc,char**argv){ProgramA PA;PA.FunA1();ProgramB PB;PB.FunB1(&ProgramA::FunA2,&PA);// 此处都要加& }
#includeclassProgramA{public:voidFunA1(){printf("I'am ProgramA.FunA1() and be called..\n");}voidFunA2(){printf("I'am ProgramA.FunA2() and be called..\n");}staticvoidFunA2Wrapper(void*context){printf("I'am ProgramA.FunA2Wrapper() and be called..\n");((ProgramA *)context)->FunA2();// 此处调用的FunA2()是context的函数, 不是this->FunA2()} };classProgramB{public:voidFunB1(void(ProgramA::*callback)(),void*context){printf("I'am ProgramB.FunB1() and be called..\n");((ProgramA *)context->*callback)();}voidFunB2(void(*callback)(void*),void*context){printf("I'am ProgramB.FunB2() and be called..\n");callback(context);} };intmain(int argc,char**argv){ProgramA PA;PA.FunA1();ProgramB PB;PB.FunB1(&ProgramA::FunA2,&PA);// 此处都要加&printf("\n");PB.FunB2(ProgramA::FunA2Wrapper,&PA); }
#include#include// fucntion/bindclassProgramA{public:voidFunA1(){printf("I&#39;am ProgramA.FunA1() and be called..\n");}voidFunA2(){printf("I&#39;am ProgramA.FunA2() and be called..\n");}staticvoidFunA3(){printf("I&#39;am ProgramA.FunA3() and be called..\n");} };classProgramB{typedef std::function<void()> CallbackFun;public:voidFunB1(CallbackFun callback){printf("I&#39;am ProgramB.FunB2() and be called..\n");callback();} };voidnormFun(){printf("I&#39;am normFun() and be called..\n");}intmain(int argc,char**argv){ProgramA PA;PA.FunA1();printf("\n");ProgramB PB;PB.FunB1(normFun);printf("\n");PB.FunB1(ProgramA::FunA3);printf("\n");PB.FunB1(std::bind(&ProgramA::FunA2,&PA)); }