C++ c++;将std::函数从另一个类传递给构造函数

C++ c++;将std::函数从另一个类传递给构造函数,c++,std,std-function,C++,Std,Std Function,我正在将一个方法传递给构造函数,但当我使用另一个类的方法时,它会给我一个错误 它目前正以这种形式运作 unsigned int pHash(const std::string& str) { //method } int main() { //stuff HashMap* hm2 = new HashMap(pHash); //stuff } 但是,如果我像这样引用另一个头文件的方法 HashMap* hm2 = new HashMap(&HashFcn::primeH

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

它目前正以这种形式运作

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.0\vc\include\xrefwrap 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.0\vc\include\xrefwrap 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.0\vc\include\xrefwrap 273 1   Project
我的hashmap构造函数如下所示

HashMap::HashMap(HashFunction hashFunction)
    : hfunc(hashFunction)
其中,hfunc是方法的类型定义

我有一个类HashFcn,它的方法是primeHash

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

这是我第一次做typdef/methodpassing——任何线索或帮助都将不胜感激

尝试将primeHash设置为静态:

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

作品是因为&HashFcn::primeHash引用了类的方法而不是对象的方法吗?另外,有没有办法通过HashMap的参数来设置对象的方法,而不是将方法设置为静态的?@RichardLee:我想你的HashFunction是一个常规函数,而不是一个方法。静态成员函数的行为类似于常规函数,但非静态成员函数则不同,因为它需要“this”的值。@RichardLee:如果您使用的是C++11,则可以使用std::function处理绑定成员函数或常规函数。非常感谢沃恩。我想知道为什么它一直要求“更多”参数。我将进一步研究“this”与std::函数加载之间的关系。