C++虚函数和函数指针一起使用,写起来有点麻烦。
下面贴出一份示例代码,可作参考。(需要支持C++11编译)
#include <stdio.h>
#include <list>
using namespace std; class VirtualWithCallBack {
public:
using CallBack = void(VirtualWithCallBack::*)(int); public:
virtual void testCallBack(int arg) = ; virtual CallBack getCallBack() const = ;
}; class VirtualWithCallBackSample1 : public VirtualWithCallBack {
public:
VirtualWithCallBackSample1() {
callBack = &VirtualWithCallBack::testCallBack;
} public:
void testCallBack(int arg) override {
printf("This is virtual call 1 : arg = %d\n", arg);
} CallBack getCallBack() const override {
return callBack;
} private:
CallBack callBack = nullptr;
}; class VirtualWithCallBackSample2 : public VirtualWithCallBack {
public:
VirtualWithCallBackSample2() {
callBack = &VirtualWithCallBack::testCallBack;
} public:
void testCallBack(int arg) override {
printf("This is virtual call 2 : arg = %d\n", arg);
} CallBack getCallBack() const override {
return callBack;
} private:
CallBack callBack = nullptr;
}; class VirtualCaller {
public:
void push(VirtualWithCallBack* callBack) {
callBackList.push_back(callBack);
} void run() {
for (auto r : callBackList) {
(r->*(r->getCallBack()))();
}
} private:
list<VirtualWithCallBack*> callBackList;
}; int main() {
VirtualCaller caller;
caller.push(new VirtualWithCallBackSample1());
caller.push(new VirtualWithCallBackSample2());
caller.run();
return ;
}
运行结果
本文由 哈萨雅琪 原创,转载请注明出处。