如何在C++中创建一个抽象类,该抽象类具有一些我想在子类中重写的抽象方法? .h 文件应如何显示?是否有一个.cpp ,如果看起来应该怎样?
在Java中,它看起来像这样:
abstract class GameObject
{
public abstract void update();
public abstract void paint(Graphics g);
}
class Player extends GameObject
{
@Override
public void update()
{
// ...
}
@Override
public void paint(Graphics g)
{
// ...
}
}
// In my game loop:
List<GameObject> objects = new ArrayList<GameObject>();
for (int i = 0; i < objects.size(); i++)
{
objects.get(i).update();
}
for (int i = 0; i < objects.size(); i++)
{
objects.get(i).paint(g);
}
对于我来说,将此代码转换为C++就足够了。
编辑:
我创建了代码,但是当我尝试遍历对象时,出现以下错误:
Game.cpp:17: error: cannot allocate an object of abstract type ‘GameObject’
GameObject.h:13: note: because the following virtual functions are pure within ‘GameObject’:
GameObject.h:18: note: virtual void GameObject::Update()
GameObject.h:19: note: virtual void GameObject::Render(SDL_Surface*)
Game.cpp:17: error: cannot allocate an object of abstract type ‘GameObject’
GameObject.h:13: note: since type ‘GameObject’ has pure virtual functions
Game.cpp:17: error: cannot declare variable ‘go’ to be of abstract type ‘GameObject’
GameObject.h:13: note: since type ‘GameObject’ has pure virtual functions
使用此代码:
vector<GameObject> gameObjects;
for (int i = 0; i < gameObjects.size(); i++) {
GameObject go = (GameObject) gameObjects.at(i);
go.Update();
}
Best Answer-推荐答案
在Java中,默认情况下,所有方法均为virtual ,除非您将其声明为final 。在C++中,这是另一种方式:您需要显式声明方法virtual 。为了使它们成为纯虚拟的,您需要将它们“初始化”为0 :-)如果您的类中具有纯虚拟的方法,它将自动变为抽象-没有显式关键字。
在C++中,您应该(几乎)始终为基类virtual 定义析构函数,以避免棘手的资源泄漏。因此,我将其添加到以下示例中:
// GameObject.h
class GameObject
{
public:
virtual void update() = 0;
virtual void paint(Graphics g) = 0;
virtual ~GameObject() {}
}
// Player.h
#include "GameObject.h"
class Player: public GameObject
{
public:
void update();
void paint(Graphics g);
}
// Player.cpp
#include "layer.h"
void Player::update()
{
// ...
}
void Player::paint(Graphics g)
{
// ...
}
关于java - C++:使用抽象方法创建抽象类,并在子类中重写该方法,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/2936844/
|