C++添加项目

C++ add items

本文关键字:项目 添加 C++      更新时间:2023-10-16

我刚接触C++,在使用列表时遇到问题。我不明白为什么我在下面的例子中出错。

GameObject类是一个抽象类玩家类和子弹类继承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();
    }
}