如何在C++中重写

How do I override in C++?

本文关键字:重写 C++      更新时间:2023-10-16

我无法让方法重写工作。现在我有一个名为Sprite的类和两个子类;让我们称他们为Goomba和Koopa。Koopas和Goombas的实例存储在一个名为spriteList的sprite的std::列表中,迭代器遍历该列表并调用每个sprite的behave()函数。

通过将行为函数定义为Sprite::behavio(),我可以将其单独用于Goombas。但是,如果我试图对Koopas做同样的事情,编译器会很生气,因为在Goomba中已经定义了Sprite::behavio()。我做错了什么?我觉得答案是一个极其简单的语法问题,但在网上查看并没有发现与我的代码非常相似的示例。

我会粘贴一些代码,希望它能有所帮助。这不是我的确切源代码,所以我为任何拼写错误道歉。

//Sprite.h:
#ifndef SPRITE_H
#define SPRITE_H
class Sprite {
private:
    float xPosition; float yPosition;
public:
    Sprite(float xp, float yp);
    void move(float x, float y); //this one is defined in Sprite.cpp
    void behave(); //this one is NOT defined in Sprite.cpp
};
#endif 

//Goomba.h:
#ifndef GOOMBA_H
#define GOOMBA_H
#include "Sprite.h"
class Goomba : public Sprite {
public:
    Goomba(float xp, float yp);
    void behave();
};
#endif 

//Goomba.cpp:
#include "Goomba.h"
Goomba::Goomba(float xp, float yp): Enemy(xp, yp) {}
void Sprite::behave(){
    Sprite::move(1, 0);
}

//Koopa.h looks just like Goomba.h

//Koopa.cpp
#include "Koopa.h"
Koopa::Koopa(float xp, float yp): Enemy(xp, yp) {}
void Sprite::behave(){
    Sprite::move(-2, 1);
}

Sprite中,您必须将函数声明为virtual

virtual void behave();

然后在Goomba中,您应该声明您将要转到具有功能的override

virtual void behave() override;

注意override关键字是C++11 的新关键字

Koopa.cppGoomba.cpp中都定义了Sprite::behave。这导致了两个定义,正如您的工具链告诉您的那样。您希望在这些文件中分别定义Koopa::behaveGoomba::behave

您还想在Sprite.cpp中定义Sprite::behave(您说过目前没有在任何地方定义它)。

您还希望使Sprite::behave成为一个虚拟函数,以便在按照您可能期望的方式工作后获得多态行为:

class Sprite {
  // ...
  // You can either define Sprite::behave in Sprite.cpp or change the declaration to:
  // virtual void behave() = 0;
  // to make it "pure virtual," indicating that subclasses must provide an implementation.
  virtual void behave();
};

Goomba.cpp中,例如:

#include "Goomba.h"
Goomba::Goomba(float xp, float yp): Enemy(xp, yp) {}
void Goomba::behave(){
  ...
}