记录两种可以间接调用类成员函数的方法,一种是直接使用函数指针,另一种使用C++11的function模板配合bind函数实现对固定类对象的成员函数调用。
定义类,新建类的对象
class Cfun {
public:
void fun(int x) {
cout << x << endl;
}
};
Cfun cf, *p = &cf;
通过函数指针调用类成员函数
void call_Cfun1(void (Cfun::*fun_)(int), Cfun &obj, int v) {
(obj.*fun_)(v);
}
int main(){
//函数指针
void (Cfun::*fp)(int);
fp = &Cfun::fun;
// (p->*fp)(2);
call_Cfun1(fp, *p, 2);
//两种方式定义函数指针的别名
typedef void (Cfun::*name1)(int);
name1 fp2 = &Cfun::fun;
// (p->*fp2)(3);
call_Cfun1(fp2, *p, 3);
using name2 = void (Cfun::*)(int);
name2 fp3 = &Cfun::fun;
// (p->*fp3)(4);
call_Cfun1(fp3, *p, 4);
}
通过function模板配合bind函数实现对固定类对象的成员函数调用
void call_Cfun2(function<void(int)> fun_, int v) {
fun_(v);
}
int main(){
// function模板配合bind函数
function<void(int)> fp4 = std::bind(&Cfun::fun, cf, std::placeholders::_1);
// fp4(5);
call_Cfun2(fp4, 5);
}
总结: 第一种方法相对灵活,成员函数的指针和类对象保持分离,第二种方法适用于需调用固定类对象的成员函数的情况。