来自其他类C ++的函数指针

时间:2015-12-07 00:21:55

标签: c++ function pointers dictionary

我在使用c ++调用map中的函数指针时遇到问题。

这是我的函数指针类型:

typedef int (AEvent::*setFunction)();

这是我的地图:

std::map<const std::string, setFunction *>      _actions;

所以我发现我的功能如下:

auto mem = this->_actions.find("SHOOT")->second;

现在我怎么称呼这个功能?

提前感谢您的回复。

1 个答案:

答案 0 :(得分:1)

假设您的类层次结构如下:

class AEvent
{
public:
    virtual int Bar() = 0;
};

class Derived : public AEvent
{
public:
    virtual int Bar() override
    {
        // Return something.
        return 100;
    }
};

您可以调用指向虚拟的成员函数的指针,如下所示:

AEvent * my_object = GetDerived();

auto func = this->_actions.find("SHOOT")->second;

(my_object->*func)() // Invoke 'func'

如果你调用指向成员函数的指针,请记住你有责任正确地提供this指针,在这种情况下恰好是my_object

相关问题