如何用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