C++列表 - 添加项目

问题描述:

我是C++新手,使用列表时出现问题。我不明白为什么我在下面的示例中出现错误。C++列表 - 添加项目

游戏对象类是一个抽象类 Player类和子弹类继承游戏对象类

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()被调用。

+0

哪些错误?你可以说得更详细点吗? – Baltasarq

+0

@Baltasarq我猜错误的地方,他是poop9ng通过一个矢量完整的处置对象?可能是SEGFAULTS – CompuChip

+0

为什么你需要'list gameObjects = list ();'?我的意思是初始化部分。 – Mahesh

foreach语法是错误的,实际上,更多的是,遍历列表中的每一个元素,使其:

for (GameObject *obj : gameObjects) 
{ 
    obj->Update(); 
} 

或者,预C++ 11:

for(std::list<GameObject*>::iterator itr = gameObjects.begin(); itr != gameObjects.end(); ++itr) 
{ 
    (*itr)->Update(); 
} 

另外,您正在创建一个Bullet对象,其范围为if (canShoot),并将其地址推送到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(); 
    } 
} 
+0

谢谢你的回答:)。但现在编译器告诉我:错误\t C2259 \t'GameObject':无法实例化抽象类 – user2837445

+0

@ user2837445回答更新,使用堆分配。 –