简体   繁体   English

C ++列表-添加项目

[英]C++ list - add items

I'm new to C++ and have a problem using list. 我是C ++的新手,使用列表时遇到了问题。 I can't understand why i'm getting an error in the example bellow. 我不明白为什么我在下面的例子中出现错误。

GameObject class is an abstract class Player class and Bullet class inherit GameObject class 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
    }
}

The error is Debug Error -Abort() Has Been Called. 错误是调试错误-Abort()已被调用。

Your foreach syntax is just wrong, and actually, more is, to loop over every element in the list make it: 您的foreach语法只是错误的,实际上,更多的是,遍历列表中的每个元素使其成为:

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

Or, pre C++11: 或者,在C ++ 11之前:

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

Also, you are creating a Bullet object in the scope of if (canShoot) and push it's address to the std::list<GameObject*> . 另外,您正在if (canShoot)范围内创建Bullet对象,并将其地址推送到std::list<GameObject*> By the time you reach your foreach the Bullet object will already have been destroyed and thus your pointers in the list are dangling. 到您到达foreachBullet对象已经被破坏,因此列表中的指针悬空了。

Dynamically allocate your objects on the heap: 在堆上动态分配对象:

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