C++类成员函数指针
2020-04-09 本文已影响0人
选牌
函数指针可以写成return_type (func_name)(args...),由于类静态函数和全局函数类似,可以用函数指针来调用,对于成员函数,则需要定义成return_type (T::func_name)(args...) [const]
#include <vector>
#include <iostream>
#include <map>
using namespace std;
class MemberFuncTest{
public:
int add(int a, int b){
return a + b;
}
int dec(int a, int b){
return a - b;
}
int mul(int a, int b){
return a * b;
}
int div(int a, int b){
return a / b;
}
static int test_static(){
cout<<"I am static func"<<endl;
}
};
typedef int (MemberFuncTest::*func)(int, int);
map<int, func> func_mp = {{1, &MemberFuncTest::add}, {2,&MemberFuncTest::dec},
{3,&MemberFuncTest::mul}, {4, & MemberFuncTest::div}};
//静态成员函数和
typedef int (*func_static)();
int test1(MemberFuncTest m, int a, int b, int type){
return (m.*func_mp[type])(a, b);
}
int test1(MemberFuncTest* m, int a, int b, int type){
return (m->*func_mp[type])(a, b);
}
void test2(func_static f){
f();
}
int main(){
for(int i = 1;i <= 4; i++){
cout<<test1( MemberFuncTest(), 6, 2, i)<<" ";
cout<<test1(new MemberFuncTest(), 6, 2, i)<<endl;
}
test2(MemberFuncTest::test_static);
}