最近自己在瞎折腾,思考起了如下问题。
类如下:
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++中,如题所述的函数指针数组是如何声明、定义和使用的。是否这种使用方法是有问题的?另外具体实践中是否有类似的使用场景?
See the section Pointers to member functions in Pointer declaration.
In addition, similar scenarios may consider the Template method pattern in the design pattern.
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:
If you want to encapsulate an object and member function into a directly called function, you can refer to std::function std::bind
You can also do this
((CustomSort*)0->*(_psf[i]))(s, data_len)
If nothing goes wrong