Come creare in C++ una classe astratta con alcuni metodi astratti che voglio sovrascrivere in una sottoclasse? Come dovrebbe apparire il file .h
? C'è un .cpp
, se sì, come dovrebbe essere?C++: creare una classe astratta con metodo astratto e sovrascrivere il metodo in una sottoclasse
In Java sarebbe simile a questa:
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);
}
Traducendo questo codice in C++ è abbastanza per me.
Edit:
ho creato il codice, ma quando provo a iterare gli oggetti ottengo l'errore seguente:
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 questo codice:
vector<GameObject> gameObjects;
for (int i = 0; i < gameObjects.size(); i++) {
GameObject go = (GameObject) gameObjects.at(i);
go.Update();
}
Il codice "nel mio ciclo di gioco" è ... incompleto, nella migliore delle ipotesi. Cosa sono gli 'oggetti'? Se non ne possiedi già uno, ti consiglio vivamente di ottenere uno dei libri per principianti da [La guida e l'elenco libri definitivi di C++] (http://stackoverflow.com/questions/388242/the-definitive-c-book-guide -e-list). –
Si potrebbe anche consultare l'articolo di Herb Sutter, [Virtuality] (http://www.gotw.ca/publications/mill18.htm), che discute molte best practice quando si utilizzano funzioni virtuali ed ereditarietà in C++. –