Heim  >  Fragen und Antworten  >  Hauptteil

c++ - 如何声明、定义和使用一个指向类的成员函数的函数指针数组

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

类如下:

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

伊谢尔伦伊谢尔伦2715 Tage vor648

Antworte allen(4)Ich werde antworten

  • PHPz

    PHPz2017-04-17 13:20:56

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

    参见 Pointer declaration 中 Pointers to member functions 小节。

    另外,类似的场景也许可以考虑设计模式中的模板方法模式(Template method pattern)。

    Antwort
    0
  • PHPz

    PHPz2017-04-17 13:20:56

    must use '.*' or '->*' to call pointer-to-member function
    因为单独的非静态成员函数并不是一个callable object,你得用对应得类型的实例来调用它,譬如:

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

    如果你想把一个对象和成员函数封装成一个直接调用的函数,可以参考std::function std::bind

    Antwort
    0
  • PHP中文网

    PHP中文网2017-04-17 13:20:56

    #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;
    }

    Antwort
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:20:56

    也可以这么干((CustomSort*)0->*(_psf[i]))(s, data_len)如果不出错的话

    Antwort
    0
  • StornierenAntwort