【问题标题】:c++ calling function when using map of function pointerc++ 使用函数指针映射时调用函数
【发布时间】: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-&gt;*second)(); 这似乎是应该如何完成的,我收到以下错误: error: ‘second’ was not declared in this scope

如果我这样调用函数: (*it-&gt;second)(); 这是我从这个线程中得到的:Using a STL map of function pointers,我收到以下错误: error: invalid use of unary ‘ * ’ on pointer to member

如果有人可以帮助我,我会非常高兴。提前感谢所有即将到来的答案。

PS:知道“map”还是“unordered_map”是解决这个问题的更好方法也很有趣。

正如我所说,提前致谢: 国标

【问题讨论】:

  • 提出的重复问题或搜索“调用指向成员函数的指针”是否帮助您解决了问题?
  • 在地图中使用 const char * 作为键存在问题。而且没有理由让它变得更糟,将其转换为char *
  • 使用指针作为映射键不太可能很好地工作。而且遍历地图寻找键并不是使用地图的方式。
  • 我不认为这与上述问题完全相同。有两个运算符-&gt;*.*,这两个问题分别涵盖了它们。

标签: c++ dictionary member-function-pointers


【解决方案1】:

困难可能在于它同时是一个映射,并且它涉及指向成员的指针,这使得调用的语法更加复杂,其中包含许多必须在正确位置的括号。我认为应该是这样的:

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

或者,正如 Rakete1111 指出的那样,以下方法也可以:

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

(请注意,后者不那么冗长,但对于那些不把运算符优先级放在首位的人来说也不太容易阅读)。

【讨论】:

  • 是的,但你不需要嵌套的:(this-&gt;*it-&gt;second)() 也可以。
  • 这很好。 -&gt; 确实比-&gt;* 具有更高的优先级。我添加了它,但个人还是更喜欢额外的括号以提高可读性。
  • 实际上,我会拆分它:const auto fp = it-&gt;second; (this-&gt;*fp)();,指向成员函数的指针非常复杂,值得一提。
猜你喜欢
  • 2011-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-11
  • 2012-04-16
相关资源
最近更新 更多