这是我在这个网站上的第一篇文章。我正在一个项目中,我用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
类的静态成员函数,以保持它的接近。静态成员函数和非静态成员函数之间存在根本区别。静态成员函数不是在特定对象上调用的,因此与普通函数的关系更接近。