-
首先定义对应指针类型
typedef int(Test::*TestFunc)(int,int);
-
注册使用
通过关键字注册,再通过关键字进行调用对应成员方法,这种比用
if else/ switch case
要快速得多#include<stdio.h> #include<map> #include<string> #define TESTADD 1 #define TESTLESS 2 #define TESTMINUS 3 class Test { public: typedef int(Test::*TestFunc)(int,int); public: Test() { funcs[1]=&Test::add; funcs[2]=&Test::less; funcs[3]=&Test::minus; } int less(int a,int b){return a<b;} int add(int a, int b){return a+b;} int minus(int a, int b){return a-b;} int calc(int a,int b,TestFunc func) { return (this->*func)(a,b); } int dosome(int a,int b,int op) { return (this->*funcs[op])(a,b); } private: std::map<int,TestFunc> funcs; }; int main() { Test t; printf("%d\n",t.dosome(1,2,TESTADD)); printf("%d\n",t.dosome(1,2,TESTLESS)); printf("%d\n",t.dosome(1,2,TESTMINUS)); return 0; }
来源:oschina
链接:https://my.oschina.net/u/3695598/blog/3191109