如何用C++創建一個抽象類,並使用一些我想在子類中重寫的抽象方法? .h
文件應該怎麼看?有沒有.cpp
,如果是這樣,它應該看起來如何?C++:用抽象方法創建抽象類並重寫子類中的方法
在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();
}
你的「在我的遊戲循環」代碼是......不完整,至多。什麼是「對象」?如果你還沒有,我強烈建議從[The Definitive C++ Book Guide and List]獲得一本初學者書籍(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide -and列表)。 – 2010-05-29 22:54:37
您也可以諮詢Herb Sutter的文章[虛擬性](http://www.gotw.ca/publications/mill18。htm),其中討論了在C++中使用虛函數和繼承時的許多最佳實踐。 – 2010-05-29 22:59:53