C ++将成员函数作为参数传递给另一个成员函数

时间:2018-04-02 01:07:26

标签: c++ member-function-pointers

我想将成员方法作为参数传递给另一个成员方法。我对此进行了广泛的研究,但仍然看不出它是否正确。我的头文件如下

#include <string>
#include <map>
#include <functional>

#include "Entity.h"
#include "World.h"
#include "Item.h"

class Tile;

class Player : public Entity
{
private:
    using FunctionPointer = void (Player::*)(Tile*);
    bool victory;
    Point location;
    std::map<char, FunctionPointer> actions;

public:
    Player(std::string name, int gold, int maxHitPoints, int defensePoints, 
           Point startingLocation, int maxDamage = 0, int maxItems = -1,
           std::vector<Item*> inventory = std::vector<Item*>());

    std::string getClassName() const override;

    void printInventory(Tile*) override; 
    std::string toString() override;

    Point getLocation() const;
    Item* findMostPowerfulWeapon();
    void heal(Tile*);
    void moveNorth(Tile*);
    void moveSouth(Tile*);
    void moveEast(Tile*);
    void moveWest(Tile*);
    void attack(Tile* tile);
    void pickup(Tile* tile);
    void trade(Tile* tile);

    void getAvailableActions(Tile* tile);
    void chooseAction();

private:
    void move(int dx, int dy);
    void actionAdder(char hotkey, FunctionPointer, std::string name);
}; 

并且给我带来问题的cpp文件的一部分如下:

void Player::getAvailableActions(Tile * tile)
{
    actions.clear();
    std::cout << "Choose an action:" << std::endl;
    if (getInventory().size() > 0)
        actionAdder('i', (this->*(&Player::printInventory))(tile), "Print inventory");
    if (tile->getClassName() == "Trader")
        actionAdder('t', (this->*(&Player::trade))(tile) , "Trade");
    if (tile->getClassName() == "Monster")
        actionAdder('a', (this->*(&Player::attack))(tile), "Attack");
}

void Player::actionAdder(char hotkey, FunctionPointer action, std::string name)
{}

Visual Studio在所有这三个前面标记括号(this-&gt; *(&amp; Player :: attack))(tile),并给出工具提示“类型为”void“的参数与参数不兼容类型为“Player :: FunctionPointer”“。我尝试编译时得到的编译器错误是'void Player :: actionAdder(char,Player :: FunctionPointer,std :: string)':无法将参数2从'void'转换为'Player :: FunctionPointer'。 / p>

如果有人知道我做错了什么,我会很感激任何建议。如果您需要查看更多代码或更多详细信息,请通知我。代码不是超级秘密。

由于

1 个答案:

答案 0 :(得分:2)

仔细阅读错误消息:

  

类型&#34; void&#34; 的参数与类型参数

不兼容

  

无法将参数2从&#39; void&#39; 转换为&#39; Player::FunctionPointer&#39;。

那是因为参数2在这里:

actionAdder('i', (this->*(&Player::printInventory))(tile), "Print inventory");

实际上是调用 printInventory并尝试将该调用的结果传递给actionAdder()。但这是一个void函数,你无法将void类型的东西传递给其他东西 - 因此错误就是抱怨这个错误。

您不想调用printInventory,您只想传递一个指向它的指针。那只是:

actionAdder('i', &Player::printInventory, "Print inventory");
相关问题