C 将std ::函数从另一个类带到构造函数

c++ passing std::function from another class to a constructor

本文关键字:构造函数 另一个 std 函数      更新时间:2023-10-16

我将方法传递到构造函数中,但是当我使用另一个类的方法时,它会给我一个错误。

当前正在以此形式工作

unsigned int pHash(const std::string& str)
{
    //method
}
int main()
{
//stuff
HashMap* hm2 = new HashMap(pHash);
//stuff
}

但是,如果我引用另一个标头文件的方法,则

HashMap* hm2 = new HashMap(&HashFcn::primeHash);

我在运行时会出错,并带有以下消息;

Error   1   error C2100: illegal indirection    c:program files (x86)microsoft visual studio 11.0vcincludexrefwrap 273 1   Project
    Error   2   error C2440: 'newline' : cannot convert from 'const std::string *' to 'const HashFcn *' c:program files (x86)microsoft visual studio 11.0vcincludexrefwrap 273 1   Project
    Error   3   error C2647: '.*' : cannot dereference a 'unsigned int (__thiscall HashFcn::* )(const std::string &)' on a 'const std::string'  c:program files (x86)microsoft visual studio 11.0vcincludexrefwrap 273 1   Project

我的hashmap构造函数看起来像这样;

HashMap::HashMap(HashFunction hashFunction)
    : hfunc(hashFunction)

其中hfunc是方法的类型。

我有一个具有PrimeHash方法的hashfcn

unsigned int primeHash(const std::string&);

这是我第一次进行Typdef/方法传递 - 任何线索或帮助都将不胜感激!

尝试使PrimeHash静态:

  static unsigned int primeHash(const std::string&);