¿Cómo crear en C++ una clase abstracta con algunos métodos abstractos que deseo sobrescribir en una subclase? ¿Cómo debería verse el archivo .h
? ¿Hay un .cpp
? En caso afirmativo, ¿cómo debería ser?C++: Crear clase abstracta con método abstracto y anular el método en una subclase
En Java se vería así:
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);
}
La traducción de este código en C++ es suficiente para mí.
Editar:
creé el código, pero cuando trato de iterar sobre los objetos consigo error siguiente:
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
Con este código:
vector<GameObject> gameObjects;
for (int i = 0; i < gameObjects.size(); i++) {
GameObject go = (GameObject) gameObjects.at(i);
go.Update();
}
Su código "en mi bucle de juego" es ... incompleto, en el mejor de los casos. ¿Qué es 'objetos'? Si todavía no tiene uno, le recomiendo que obtenga uno de los libros para principiantes de [The Definitive C++ Book Guide and List] (http://stackoverflow.com/questions/388242/the-definitive-c-book-guide -y-lista). –
También puede consultar el artículo de Herb Sutter, [Virtuality] (http://www.gotw.ca/publications/mill18.htm), que analiza muchas mejores prácticas al usar funciones virtuales y herencia en C++. –