【问题标题】:C++ function parameter defined by children [duplicate]子项定义的C ++函数参数[重复]
【发布时间】:2017-07-07 04:44:40
【问题描述】:

我有一个实体类来处理实体的选择。在这个类中,我有一个函数向量,它传递给 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

【问题讨论】:

  • 你做了什么?请向我们展示您的尝试。
  • 代码说一千多张图片。请尝试创建Minimal, Complete, and Verifiable Example 并展示给我们。
  • 我已经添加了我的尝试
  • calculateFOV的类型是什么?
  • 现在将其添加到问题中。

标签: c++ function inheritance


【解决方案1】:

calculateFOV 是一个非静态成员函数,所以它有一个隐含的this 参数。将其地址设为&amp;PlayableCharacter::calculateFOV 会产生void (PlayableCharacter::*)() 类型,一个指向成员函数的指针 或PTMF,它与void(*)() 不兼容。

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

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

然后,

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

【讨论】:

  • 我只是在更改std::vector&lt;void (Entity::*)() dropDownFunctions&gt; 还是有别的?无论有没有 chage,都会出现同样的错误:argument types are: (void (PlayableCharacter::*)())object type is: std::vector&lt;void(Entity::*)(), std::allocator&lt;void(Entity::*)()&gt;
  • @genfy 抱歉,转换需要明确,即static_cast。它只是隐含地从基础到派生,这通常看起来是倒退的。
猜你喜欢
  • 2018-09-14
  • 1970-01-01
  • 2021-01-30
  • 2012-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多