问题描述
最近自己在瞎折腾,思考起了如下问题。
类如下:
class CustomSort{public: bool SortFunc1(int *s, int data_len) {// TODO: }bool SortFunc2(int *s, int data_len) {// TODO: }bool SortFunc3(int *s, int data_len) {// TODO: }void ShowLog(void) {// TODO: }};typedef bool (CustomSort::*sort_func)(int *, int);
主函数如下:
int main(){ int i; sort_func _psf[3]; CustomSort a; int s*; int data_len;// TODO:_psf[0] = &CustomSort::SortFunc1; _psf[1] = &CustomSort::SortFunc2; _psf[2] = &CustomSort::SortFunc3;for (i=0; i<3; i++) {// TODO:*(_psf[i])(s, data_len);// TODO: }a.ShowLog();return 0;}
目的即是想在循环中依次调用CustomSort中的3个成员来处理一下数组s中的数据。
但build报出通过函数指针调用函数的语句存在错误:
error: must use ’.*’ or ’->*’ to call pointer-to-member function in ’_psf[i] (...)’, e.g. ’(... ->* _psf[i]) (...)’
所以不是很明白C++中,如题所述的函数指针数组是如何声明、定义和使用的。是否这种使用方法是有问题的?另外具体实践中是否有类似的使用场景?
问题解答
回答1:(a.*_psf[i])(s, data_len);
参见 Pointer declaration 中 Pointers to member functions 小节。
另外,类似的场景也许可以考虑设计模式中的模板方法模式(Template method pattern)。
回答2:must use ’.*’ or ’->*’ to call pointer-to-member function因为单独的非静态成员函数并不是一个callable object,你得用对应得类型的实例来调用它,譬如:
(a.*(_psf[i]))(s, data_len);
如果你想把一个对象和成员函数封装成一个直接调用的函数,可以参考std::function std::bind
回答3:#include <cstdio>#include <cstdlib>using namespace std;class zz{private: int x;public: zz():x(0){} zz(int x_):x(x_){} void add(int y){printf('%dn',x+y);} void sub(int y){printf('%dn',x-y);} void multi(int y){printf('%dn',x*y);} void p(int y){printf('%dn',x/y);}};typedef void (zz::* pf)(int);pf calc[]={&zz::add,&zz::sub,&zz::multi,&zz::p};int main(){ zz a(60),*p=&a; for(int i=0;i<4;++i) (a.*calc[i])(2); for(int i=0;i<4;++i) (p->*calc[i])(3); return 0;}回答4:
也可以这么干((CustomSort*)0->*(_psf[i]))(s, data_len)如果不出错的话