首頁  >  問答  >  主體

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 天前647

全部回覆(4)我來回復

  • PHPz

    PHPz2017-04-17 13:20:56

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

    參考 Pointer declaration 中 Pointers to member functions 小節。

    另外,類似的場景或許可以考慮設計模式中的模板方法模式(Template method pattern)。

    回覆
    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

    回覆
    0
  • PHP中文网

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

    雷雷

    回覆
    0
  • 巴扎黑

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

    也可以這麼乾((CustomSort*)0->*(_psf[i]))(s, data_len)如果不出錯的話

    回覆
    0
  • 取消回覆