[英]C++ list - add items
我是C ++的新手,使用列表时遇到了问题。 我不明白为什么我在下面的例子中出现错误。
GameObject类是抽象类Player类,Bullet类继承了GameObject类
list<GameObject*> gameObjects = list<GameObject*>();
gameObjects.push_front(&player);
while(gameLoop)
{
if (canShoot)
{
Bullet b = Bullet(player.Position.X , player.Position.Y);
gameObjects.push_front(&b);
}
for each (GameObject *obj in gameObjects)
{
(*obj).Update(); // get an error
}
}
错误是调试错误-Abort()已被调用。
您的foreach
语法只是错误的,实际上,更多的是,遍历列表中的每个元素使其成为:
for (GameObject *obj : gameObjects)
{
obj->Update();
}
或者,在C ++ 11之前:
for(std::list<GameObject*>::iterator itr = gameObjects.begin(); itr != gameObjects.end(); ++itr)
{
(*itr)->Update();
}
另外,您正在if (canShoot)
范围内创建Bullet
对象,并将其地址推送到std::list<GameObject*>
。 到您到达foreach
, Bullet
对象已经被破坏,因此列表中的指针悬空了。
在堆上动态分配对象:
list<GameObject*> gameObjects;
while(gameLoop)
{
if (canShoot)
{
Bullet* b = new Bullet(player.Position.X , player.Position.Y);
gameObjects.push_front(b);
}
for (GameObject* obj : gameObjects)
{
obj->Update();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.