我在一个名为Level的类中工作,我将指针存储到地图内部该类的两个成员函数中。在另一个称为"更新"的函数中,我正在使用用户输入,然后通过地图进行迭代,首先比较键,然后(尝试)使用功能指针调用相应的功能。但是,到目前为止,我尝试过的任何事情都没有起作用(使用std ::不同的迭代器而不是普通函数指针,并尝试通过该类对象的指针调用该函数)。我是否错过了明显的东西,还是对此采取不正确的方法?
相关代码下面:
Level.h
// Create function pointers to store in the map
void(Level::*examine)() = &Level::Examine;
void(Level::*display)() = &Level::Display;
// Data structures
std::map<std::string, void(Level::*)()> actionsMap;
Level.cpp
void Level::Update(bool &gameState) {
// Display something to the user
std::cout << "You have reached the " << name << " level. Please perform an action.n";
// Get user input
std::cin >> inputString;
// Split the string into words and store them in compareVector
compareVector = inputParser->Split(inputString, ' ');
// Check is the first noun can be handled by outputHandler functions
outputHandler->Compare(compareVector[0], gameState);
// Iterate through the actionsMap
for (auto it: actionsMap) {
// If the key matches the first word, call the corresponding function
if (it.first == compareVector[0]) {
// Call the function - gives an error as it.second is not a pointer-to-function type
it.second();
}
}
// Clear the vector at the end
compareVector.clear();
}
对象可以通过a 成员函数函数pointer 呼叫需要->*
或.*
操作员。因此,您可能想做:
// If the key matches the first word, call the corresponding function
if (it.first == compareVector[0]) {
// Call the function - gives an error as it.second is not a pointer-to-function type
(this->*(it.second))();
//Or
((*this).*(it.second))();
}
为了使表达式有效,需要额外的括号,否则操作员的优先级使其无效。
另一个选项是使用std::mem_fn
// If the key matches the first word, call the corresponding function
if (it.first == compareVector[0]) {
// Call the function - gives an error as it.second is not a pointer-to-function type
std::mem_fn(it.second)(this);
}
查看 live
您可以做类似:
的事情auto it = actionsMap.find(compareVector[0]));
if (it != actionsMap.end()) {
(this->*(it->second))();
}