一、类成员函数的回调
1. 类成员函数的回调,函数的调用必须通过类来调用;
CallBack.h
#pragma once class CallBack { public: CallBack(); ~CallBack(); typedef void (CallBack::*pFunc)(int); void printFunc(int x); void FuncCall(CallBack *obj, CallBack::pFunc p); };
CallBack.cpp
#include "CallBack.h" #include <stdio.h> CallBack::CallBack() { } CallBack::~CallBack() { } void CallBack::printFunc(int x) { printf("CALLBACK x value is %d\n", x); } void CallBack::FuncCall(CallBack *obj, CallBack::pFunc p) { int x = 5; (obj->*p)(x); }
main.cpp
#include "CallBack.h" int main() { CallBack *cb = new CallBack(); cb->FuncCall(cb, &CallBack::printFunc); return 0; }
运行结果为:
二、静态函数的回调
注意:1. 静态函数只能在声明这个函数的文件中调用;
CallBack.h
#pragma once typedef void(*pFunc)(int); static void printFunc(int x); void FuncCall(pFunc p, int x); void excute(int x);
CallBack.cpp
#include "CallBack.h" #include <stdio.h> static void printFunc(int x) { printf("CALLBACK x value is %d\n", x); } void FuncCall(pFunc p, int x) { (*p)(x); } void excute(int x) { FuncCall(printFunc, x); }
main.cpp
#include "CallBack.h" int main() { int x = 5; excute(x); return 0; }
运行结果为:
原文:https://www.cnblogs.com/anlia/p/9146125.html