Arduino C++ 继承和函数声明问题
Arduino C++ Inheritance and function declaration problem
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++ 继承和多态性很感兴趣。
你的classEntity
应该是这样的:
class Entity
{
public:
virtual void applyCollisionBehaviorTo(Entity &entity) = 0;
virtual void onCollision(Entity &collidingEntity) = 0;
};
你不能在Entity
中引用Ball
class的对象,事实上实体甚至不知道球的存在。
OTOH 球“知道”它们 是 个实体
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++ 继承和多态性很感兴趣。
你的classEntity
应该是这样的:
class Entity
{
public:
virtual void applyCollisionBehaviorTo(Entity &entity) = 0;
virtual void onCollision(Entity &collidingEntity) = 0;
};
你不能在Entity
中引用Ball
class的对象,事实上实体甚至不知道球的存在。
OTOH 球“知道”它们 是 个实体