C++添加项目
C++ add items
我刚接触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();
}
}
相关文章:
- 将项目添加到队列时运行线程
- 如何使用矢量元素将项目添加到结构中?
- 本机 Nuget 包安装在 VS 中,但没有为C++(本机)项目添加引用
- 如何将多个 QStringList 中的项目添加到一个
- CMake 和/或在为项目添加提升时出错
- 我无法将项目添加到 ( 标准::矢量 < 标准::矢量 <标准::字符串> > )
- 计数器将项目添加到数组中,并剩余
- 将CMAKE项目添加到Visual Studio解决方案中
- 如何使用QListView项目添加复选框
- C++将项目添加到集合中
- 在MFC中的树(ctreectrl)中的特定树项目添加图标
- 如何将类的项目添加到C 的数组中,而无需给它们命名
- 如何将项目添加到输出文件中
- CMAKE将新项目添加到解决方案中
- 如何将项目添加到QT中的布局中
- 将项目添加到双向链表的背面时遇到问题
- 捕获非默认文件夹上的项目添加事件
- wxWidgets-通过DLL将项目添加到sizer
- 使用.push_back将新创建的项目添加到库存
- 如何将MFC应用程序项目添加到Visual C 2008中的Win32应用程序项目