簡體   English   中英

C ++列表-添加項目

[英]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*> 到您到達foreachBullet對象已經被破壞,因此列表中的指針懸空了。

在堆上動態分配對象:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM