Как создать в С++ абстрактный класс с некоторыми абстрактными методами, которые я хочу переопределить в подклассе? Как должен выглядеть файл .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);
}
Перевод этого кода на С++ для меня достаточно.
Edit:
Я создал код, но когда я пытаюсь выполнить итерацию по объектам, я получаю следующую ошибку:
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();
}