c++ - 如何声明、定义和使用一个指向类的成员函数的函数指针数组
伊谢尔伦
伊谢尔伦 2017-04-17 13:18:56
0
4
714

最近自己在瞎折腾,思考起了如下问题。

类如下:

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++中,如题所述的函数指针数组是如何声明、定义和使用的。是否这种使用方法是有问题的?另外具体实践中是否有类似的使用场景?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(4)
PHPzhong
(a.*_psf[i])(s, data_len);

See the section Pointers to member functions in Pointer declaration.

In addition, similar scenarios may consider the Template method pattern in the design pattern.

PHPzhong

must use '.*' or '->*' to call pointer-to-member function
Because a single non-static member function is not a callable object, you have to use an instance of the corresponding type to call it It, for example:

(a.*(_psf[i]))(s, data_len);

If you want to encapsulate an object and member function into a directly called function, you can refer to std::function std::bind

洪涛
#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("%d\n",x+y);}
    void sub(int y){printf("%d\n",x-y);}
    void multi(int y){printf("%d\n",x*y);}
    void p(int y){printf("%d\n",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;
}
巴扎黑

You can also do this((CustomSort*)0->*(_psf[i]))(s, data_len)If nothing goes wrong

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template