如何在C++中重写
How do I override in C++?
我无法让方法重写工作。现在我有一个名为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.cpp
和Goomba.cpp
中都定义了Sprite::behave
。这导致了两个定义,正如您的工具链告诉您的那样。您希望在这些文件中分别定义Koopa::behave
和Goomba::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(){
...
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- 在 C++ 中用派生类型重写成员函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 方法重写线程C++中的概念
- 为重写std::exception的库生成swig接口时出错
- 如何强制从重写方法调用重写的方法基方法?
- 用于C++的静态二进制检测或二进制重写工具和框架
- 如何将 if else 语句重写为 switch 语句
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- 用 C 重写C++类
- 是否总是可以将使用递归编写的程序重写为不使用递归的程序C++,性能观点是什么?
- 重写虚拟函数和继承
- C++调用使用重写函数的父类函数
- 重写打印函数而不是覆盖基类
- 不允许在类定义之外重写
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- C++:从抽象类重写纯虚拟运算符重载
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 重写函数不打印基类数据