由儿童定义的C ++函数参数

时间:2017-02-17 15:27:51

标签: c++ function inheritance

我有一个处理实体选择的实体类。在这个类中,我有一个函数向量,传递给UI以呈现到下拉菜单中。我希望能够在我的类中创建继承实体的函数,但是将这些函数从实体传递到UI。关于如何做到这一点的任何想法?

我做了什么?

我向实体添加了受保护的矢量:

std::vector<void (*)()> dropDownFunctions;

UI的功能:

void renderDropDown(std::vector<void(*)()> dropDownFunctions);

这就是这个功能:

private:
    void calculateFOV();

然后尝试在继承实体的类中修改向量:

dropDownFunctions.push_back(&PlayableCharacter::calculateFOV);

我收到错误:

no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=void (*)(), _Alloc=std::allocator<void (*)()>]" matches the argument list

1 个答案:

答案 0 :(得分:1)

calculateFOV是非静态成员函数,因此它具有隐式this参数。将其地址设为&PlayableCharacter::calculateFOV会产生类型void (PlayableCharacter::*)()指向成员函数的指针或PTMF,它与void(*)()不兼容。< / p>

假设PlayableCharacter来自Entity,您可以尝试:

typedef void (Entity::* DropDownFn)();
std::vector< DropDownFn > dropDownFunctions;

然后,

dropDownFunctions.push_back
                  ( static_cast< DropDownFn >( &PlayableCharacter::calculateFOV ) );