簡體   English   中英

C ++將std :: function從另一個類傳遞給構造函數

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

我正在將方法傳遞給構造函數,但是當我使用另一個類的方法時,它給我一個錯誤。

目前正在以這種形式工作;

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是方法的typdef。

我有一個類HashFcn具有方法primeHash

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

這是我第一次進行typdef /方法傳遞-任何線索或幫助將不勝感激!

嘗試使primeHash靜態:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM