【问题标题】:Arduino C++ Inheritance and function declaration problemArduino C++ 继承和函数声明问题
【发布时间】:2021-02-17 00:49:31
【问题描述】:
class Entity {
  public:
    virtual void applyCollisionBehaviorTo(Entity &entity) { }
    
    virtual void onCollision(Entity &entity) { }
};

class Ball : public Entity {
  public:
    void applyCollisionBehaviorTo(Entity entity) override {
      
    }

    void onCollision(Entity entity) override {
      entity.applyCollisionBehaviorTo(this); // error: no matching function for call to 'Entity::applyCollisionBehaviorTo(Ball*)'
    }
};

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

我来自 C# 背景,所以我正在研究 C++ 继承和多态性。

【问题讨论】:

  • 因为那时还没有声明。你以后才声明它。
  • 另外,基类不应该知道派生类!
  • 你没有。它首先使用继承打败了整个观点。您是否正在尝试实现某种双重调度?
  • 为了通过值传递Ball,您需要在使用之前对其进行完整定义。但是您可以只使用前向声明来传递指针或引用。
  • 我已更新问题以反映更多问题所在。

标签: c++ arduino


【解决方案1】:

你的班级Entity应该是这样的:

class Entity
{
public:
    virtual void applyCollisionBehaviorTo(Entity &entity) = 0;    
    virtual void onCollision(Entity &collidingEntity) = 0;
};

你不能在Entity中引用Ball类的对象,实际上实体甚至不知道球的存在。
OTOH 球“知道”它们实体

【讨论】:

  • 是的,我试过了,但是当通过 this 时,我得到:no matching function for call to 'Entity::applyCollisionBehaviorTo(Ball*)'Ball 类中。
  • 因为你必须通过*this
  • this 是一个指针。如果使用引用或值,则必须取消引用它
  • 好的很好,*this 似乎解决了我的问题 :) 谢谢。
  • 不客气,但请记住,您仍然必须匹配 Ball 中的方法签名
猜你喜欢
  • 2021-11-10
  • 2014-06-29
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 2021-06-24
  • 1970-01-01
相关资源
最近更新 更多