0

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

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

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

//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);
}
4

2 回答 2

1

Sprite您必须将函数声明为virtual

virtual void behave();

然后在Goomba你应该声明你要去override那个功能

virtual void behave() override;

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

于 2014-09-30T16:27:00.127 回答
0

In both Koopa.cpp and Goomba.cpp you are defining Sprite::behave. This results in two definitions, as your toolchain told you. You want to define Koopa::behave and Goomba::behave, respectively, in those files.

You also want to define Sprite::behave in Sprite.cpp (you said you currently do not define it anywhere).

You will also want to make Sprite::behave a virtual function in order to get the polymorphic behavior you are after working the way you likely expect it to:

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();
};

In Goomba.cpp, for example:

#include "Goomba.h"

Goomba::Goomba(float xp, float yp): Enemy(xp, yp) {}
void Goomba::behave(){
  ...
}
于 2014-09-30T16:31:58.750 回答