下面是一些代碼:傳遞函數指針作爲矢量<對<string,X>> X參數
// Unit.h
typedef void (IInteractable::*fPtr)(Player&);
typedef std::vector<std::pair<std::string, fPtr>> Actions;
// Unit.cpp
Actions Unit::getActions()
{
Actions a;
a.push_back(make_pair("Attack", &Unit::attack));
return a;
}
void attack(Player& p)
{
cout << "Attack!" << endl;
}
什麼我得到的是error: no matching function for call to ‘std::vector<std::pair<std::basic_string<char>, void (IInteractable::*)(Player&)> >::push_back(std::pair<const char*, void (Unit::*)(Player&)>)’
,其似乎不可思議原因單位從IInteractable繼承。我花了一些時間來解決這個問題「簡單」,但我不知道下一步該怎麼做。誰能幫忙?
這是行不通的。在你的例子中,它看起來沒有問題,但是如果有人出現,就會拉出vector的一個元素並調用函數指針(根據vector的def *應該是* IInteractable :: * )在'IInteractable'而不是'Unit'上的東西?然後你在一個不是'Unit'的東西上調用'Unit'成員函數,那就是* bad *。這就是爲什麼編譯器不能讓你做你想做的事情。 – us2012
相關:http://stackoverflow.com/questions/4387798/function-pointers-to-member-functions-of-a-parent-class –