首页 > 代码库 > C++虚函数和函数指针一起使用

C++虚函数和函数指针一起使用

C++虚函数和函数指针一起使用,写起来有点麻烦。

下面贴出一份示例代码,可作参考。(需要支持C++11编译)

 1 #include <stdio.h> 2 #include <list> 3 using namespace std; 4  5 class VirtualWithCallBack { 6 public: 7     using CallBack = void(VirtualWithCallBack::*)(int); 8  9 public:10     virtual void testCallBack(int arg) = 0;11 12     virtual CallBack getCallBack() const = 0;13 };14 15 class VirtualWithCallBackSample1 : public VirtualWithCallBack {16 public:17     VirtualWithCallBackSample1() {18         callBack = &VirtualWithCallBack::testCallBack;19     }20 21 public:22     void testCallBack(int arg) override {23         printf("This is virtual call 1 : arg = %d\n", arg);24     }25 26     CallBack getCallBack() const override {27         return callBack;28     }29 30 private:31     CallBack callBack = nullptr;32 };33 34 class VirtualWithCallBackSample2 : public VirtualWithCallBack {35 public:36     VirtualWithCallBackSample2() {37         callBack = &VirtualWithCallBack::testCallBack;38     }39 40 public:41     void testCallBack(int arg) override {42         printf("This is virtual call 2 : arg = %d\n", arg);43     }44 45     CallBack getCallBack() const override {46         return callBack;47     }48 49 private:50     CallBack callBack = nullptr;51 };52 53 class VirtualCaller {54 public:55     void push(VirtualWithCallBack* callBack) {56         callBackList.push_back(callBack);57     }58 59     void run() {60         for (auto r : callBackList) {61             (r->*(r->getCallBack()))(99);62         }63     }64 65 private:66     list<VirtualWithCallBack*> callBackList;67 };68 69 int main() {70     VirtualCaller caller;71     caller.push(new VirtualWithCallBackSample1());72     caller.push(new VirtualWithCallBackSample2());73     caller.run();74     return 0;75 }

 

运行结果

 


本文由 哈萨雅琪 原创,转载请注明出处。

 

C++虚函数和函数指针一起使用