【发布时间】:2017-11-24 12:25:18
【问题描述】:
我设置这个帐户主要是因为我在其他地方找不到答案。我检查了stackoverflow和不同页面上的各种教程或问题/答案。
我正在编写一个基于终端的 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”是解决这个问题的更好方法也很有趣。
正如我所说,提前致谢: 国标
【问题讨论】:
-
提出的重复问题或搜索“调用指向成员函数的指针”是否帮助您解决了问题?
-
在地图中使用
const char *作为键存在问题。而且没有理由让它变得更糟,将其转换为char * -
使用指针作为映射键不太可能很好地工作。而且遍历地图寻找键并不是使用地图的方式。
-
我不认为这与上述问题完全相同。有两个运算符
->*和.*,这两个问题分别涵盖了它们。
标签: c++ dictionary member-function-pointers