【发布时间】:2018-02-10 22:46:46
【问题描述】:
我正在一个名为 Level 的类中工作,我在其中将指向该类的两个成员函数的指针存储在一个映射中。在另一个名为 Update 的函数中,我接受用户输入,然后遍历映射,首先比较键,然后(尝试)使用函数指针调用相应的函数。但是,到目前为止,我尝试过的任何事情都没有奏效(不同的迭代器,使用 std::function 而不是普通的函数指针,并尝试通过类对象的 this 指针调用函数)。我是否遗漏了一些明显的东西,或者我对此采取了不正确的方法?
相关代码如下:
级别.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();
}
【问题讨论】:
-
你可能想做:
(this->*(it.second))() -
是的,这正是我需要做的。我猜我只是遗漏了一些明显的东西;谢谢!