gpt4 book ai didi

C++ - 带函数指针的哈希表

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

这是我在这个网站上的第一篇文章。我在一个用 C++ 编写哈希表的项目中。我对函数指针有疑问。

我有一个哈希表,其中包含一些学生(由他们的学生编号标识)。我必须使用函数指针来传递散列参数。

我的代码在:

//file main.cpp
Table t1;
unsigned int(Table::* ptrHash)(unsigned int);
ptrHash = &Table::hash;
t1.insertStudent(11507461, 20, ptrHash);

// file Table.cpp
void Table::insertStudent(unsigned int numberStudent, unsigned int (*f)(unsigned int)) {...}
unsigned int Table::hash(unsigned int cleEtu) {...}

//file Table.h
void insertStudent(unsigned int numberStudent, unsigned int (*f)(unsigned int));
unsigned int hash(unsigned int numberStudent);

我的提示给我这个错误:

no matching function for call to 'Table::insertStudent(int, unsigned int (Table::*&)(unsigned int))' t1.insererEtu(11507461, 20, ptrHachage); 
note:no known conversion for argument 3 from ‘unsigned int (Table::*)(unsigned int)’ to ‘unsigned int (*)(unsigned int)’

我知道这对它来说不一样,但我不知道如何解决它。我尝试了很多方法,但都没有效果。

如果有人能帮助我,它会救我!

最佳答案

你的问题的原因是指向普通函数的指针和指向成员函数的指针之间存在差异。函数 insertStudent 接受一个指向普通函数的指针,但您使用指向 Table 类的成员函数的指针调用它。

在这种情况下,我个人根本不会使用函数指针,我会insertStudent 在散列函数上进行参数化。这将允许散列函数成为任何具有接受 int 并返回 int 的函数调用运算符的对象。

如果我的老师强制我使用函数指针,我会将散列函数设为 Table 类的静态成员函数,以使其保持关闭状态。静态和非静态成员函数之间存在根本区别。静态成员函数不会在特定对象上调用,因此与普通函数的关系更密切。

关于C++ - 带函数指针的哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47094587/

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