Min*_*hĩa 2 c++ function-pointers
我想用自定义比较器创建一个排序函数,该函数位于一个类中.起初我遵循了我的讲师的指示,但是当它涉及成员函数时(结果指向成员和指向函数的指针是2个不同的指针,并且它们不能被视为另一个),它被证明是错误的.我按照这里显示的说明进行了操作,但它不会有任何不同 http://www.radmangames.com/programming/how-to-use-function-pointers-in-cplusplus
这是我的代码:
class llistStudent
{
public:
void sort_list(bool (*comparator)(int &, int &));
void swapStudent(int& positionA, int& positionB);
bool sort_name_ascending(int& positionA, int& positionB);
bool (llistStudent::*name_ascending)(int &, int &) = &llistStudent::method;
name_ascending = llistStudent::sort_name_ascending;
};
Run Code Online (Sandbox Code Playgroud)
以及我如何使用它:
sort_list(sort_name_ascending);
Run Code Online (Sandbox Code Playgroud)
它说:
'name_ascending' does not name a type
Run Code Online (Sandbox Code Playgroud)
我哪里做错了?谢谢!编辑:当我编辑代码在这里发布时,这是一个错字:sort_name_ascending!`
有两个问题:
1)name_ascending = llistStudent::sort_name_ascending;在课堂定义中是非法的.你不能像这样在类中随机编写随机代码.您应该将它放在某个方法中,可能是constuctor或使其成为声明者的一部分.
要解决此问题,只需在声明中初始化函数指针(仅限C++ 11及更高版本):
bool (llistStudent::*name_ascending)(int &, int &) = &llistStudent::sort_name_ascending;
Run Code Online (Sandbox Code Playgroud)
2)sort_list(sort_GPA_ascending);不会工作.sort_list期望参数类型bool (*)(int &, int &),并name_ascending具有类型bool (llistStudent::*)(int &, int &)
要解决这个问题,我们需要知道您的排序函数是否应该有权访问类内部.如果它不应该(从你的用例中看起来),你应该做它static并相应地调整指针类型:
static bool sort_name_ascending(int& positionA, int& positionB);
bool (*name_ascending)(int &, int &) = &llistStudent::sort_name_ascending;
Run Code Online (Sandbox Code Playgroud)
否则,您需要更改sort_list参数类型bool (llistStudent::*)(int &, int &).请注意,应该在类实例上调用成员函数指针(在您的情况下可能是这样*this).