gpt4 book ai didi

c++ - "does not name a type"尝试使用指向函数的指针时出错

转载 作者:搜寻专家 更新时间:2023-10-31 00:10:36 25 4
gpt4 key购买 nike

我想用自定义比较器创建一个排序函数,该函数位于一个类中。起初我按照我讲师的指示,但是当涉及到成员函数时,结果是错误的(指向成员的指针和指向函数的指针是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;
};

以及我如何使用它:

sort_list(sort_name_ascending);

它说:

'name_ascending' does not name a type

我哪里错了?谢谢!编辑:当我编辑代码以将其发布到此处时,这是一个错字:sort_name_ascending!`

最佳答案

有两个问题:

1) name_ascending = llistStudent::sort_name_ascending; 在类定义中是非法的。你不能像那样在类里面随意敲打代码。您应该将它放在某种方法中,可能是构造函数或使其成为声明器的一部分。
要解决此问题,只需在声明中初始化函数指针(仅限 C++11 及更高版本):

bool (llistStudent::*name_ascending)(int &, int &) = &llistStudent::sort_name_ascending;     

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;

否则,您需要将 sort_list 参数的类型更改为 bool (llistStudent::*)(int &, int &)。请注意,应该在类实例上调用成员函数指针(在您的情况下可能是 *this)。

关于c++ - "does not name a type"尝试使用指向函数的指针时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37572603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com