我设置了这个帐户主要是因为我在其他地方找不到答案。我检查了各种教程或在stackoverflow和不同页面上的问题/答案。使用函数指针映射时的C++调用函数
我正在编程一个基于终端的textadventure,并需要一个函数的地图。这是我得到了什么(我离开了所有的意思都没有对这个问题的东西)
#include <map>
using namespace std;
class CPlayer
{
private:
//Players functions:
typedef void(CPlayer::*m_PlayerFunction)(void); //Function-pointer points to various player
//functions
map<char*, m_PlayerFunction> *m_FunctionMap; //Map containing all player functions
public:
//Constructor
CPlayer(char* chName, CRoom* curRoom, CInventory* Inventory);
//Functions:
bool useFunction(char* chPlayerCommand);
void showDoors(); //Function displaing all doors in the room
void showPeople(); //Function displaying all people in the room
};
#endif
#include "CPlayer.h"
#include <iostream>
CPlayer::CPlayer(char chName[128], CRoom* curRoom, CInventory *Inventory)
{
//Players functions
m_FunctionMap = new map<char*, CPlayer::m_PlayerFunction>;
m_FunctionMap->insert(std::make_pair((char*)"show doors", &CPlayer::showDoors));
m_FunctionMap->insert(std::make_pair((char*)"show people", &CPlayer::showPeople));
}
//Functions
//useFunction, calls fitting function, return "false", when no function ist found
bool CPlayer::useFunction(char* chPlayerCommand)
{
CFunctions F;
map<char*, m_PlayerFunction>::iterator it = m_FunctionMap->begin();
for(it; it!=m_FunctionMap->end(); it++)
{
if(F.compare(chPlayerCommand, it->first) == true)
{
cout << "Hallo" << endl;
(it->*second)();
}
}
return false;
}
现在的问题是:
如果我叫功能是这样的: (it->*second)();
这似乎是它应该是怎样做的,我得到以下错误: error: ‘second’ was not declared in this scope
如果我调用该函数是这样的: (*it->second)();
这是我从这个线程获得:Using a STL map of function pointers,我得到以下错误: error: invalid use of unary ‘ * ’ on pointer to member
,我会很高兴,如果有人可以帮助我。感谢所有即将到来的答案。 PS:知道“map”还是“unordered_map”是解决此问题的更好方法也很有趣。提前
正如我所说的,谢谢: GB
可能重复的[如何调用成员函数指针?](https://stackoverflow.com/questions/24325612/how-do-i-call-a-member-function- pointer) – alain
提议重复的问题或搜索“调用指向成员函数的指针”可以帮助您解决问题? – nwp
在地图中使用'const char *'作为键存在问题。并且没有理由让它更糟地将它转换为'char *' – Slava