2017-06-21 185 views
1

我设置了这个帐户主要是因为我在其他地方找不到答案。我检查了各种教程或在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

+1

可能重复的[如何调用成员函数指针?](https://stackoverflow.com/questions/24325612/how-do-i-call-a-member-function- pointer) – alain

+0

提议重复的问题或搜索“调用指向成员函数的指针”可以帮助您解决问题? – nwp

+2

在地图中使用'const char *'作为键存在问题。并且没有理由让它更糟地将它转换为'char *' – Slava

回答

1

的困难可能是因为它是在同一时间一张地图,它涉及指针到成员,这使得语法调用有很多更复杂的括号必须在正确的位置。我想应该是这样的:

(this->*(it->second))() 

此外,作为Rakete1111指出,以下的作品,以及:

(this->*it->second)() 

(请注意,后者是更简洁,而且也不太容易阅读那些在他们头脑中没有运营商优先权的人)。

+0

是的,但你不需要嵌套的:'(this - > * it-> second)()'也可以。 – Rakete1111

+0

这是一个很好的观点。记录''>'确实比' - > *'具有更高的优先级。我添加了它,但仍然个人更喜欢额外的括号以提高可读性。 –

+0

其实,我会分割它:'const auto fp = it-> second; (this - > * fp)();',成员函数指针非常复杂,值得拼写出来。 –