【发布时间】:2013-12-03 22:44:18
【问题描述】:
所以我正在制作一个蹩脚的小单板滑雪游戏(这是我所有问题的主题),但我遇到了一些问题。 我有一个 Biome 类,它有一个动态数组来存储该生物群系(obstsInBiome)可能存在的障碍。这是构造函数:
Biome::Biome(Obstacle obsts[], int amountOfObsts)
{
maxObstAmount = 10; // Max amount of obstacles to spawn in each biome
obstAmount = amountOfObsts; // The amount of obstacles passed in in the obsts parameter
// This part copys the array passed in to the obstsInBiome array (Class member to store obstacles)
// I think this is where the error may be
obstsInBiome = new Obstacle [amountOfObsts]; // Creating array to hold the possible obstacles in this biome
for (int x = 0; x < amountOfObsts; x++) // Filling the obstacle array with the obstacles passed in
{
obstsInBiome[x] = obsts[x];
}
}
然后创建一个新的生物群系,我使用这个:
Obstacle villageObsts[] = {tree, rock, cabin, log}; // tree, rock, and cabin are all Obstacles
Biome village(villageObsts, 4);
在这段代码中,obstsInBiome 的第一个元素没有正确设置。
village.obstsInBiome[0] 就是我的意思。
当我尝试将其绘制到屏幕上时,它不会出现,并且玩家会发生不可见的碰撞,就好像他们撞到了障碍物一样。阵列的其余部分(岩石、小屋和原木)都工作得很好。 village.obstsInBiome[1 through 3] 一切正常。
有人能指出这段代码中的错误吗?
【问题讨论】:
-
你意识到了 VillageObsts 子对象是通过副本创建的,对,并且如果你修改正在其他地方传递的 obst,这不会影响 obstsInBiome 中包含的那些
-
你遇到了什么错误?
-
是否有其他数组越界写入?
-
在重新分配
obstsInBiome之前,您还没有释放它,从而导致内存泄漏。 -
谁是 obstsInBiome 以及 Obstacle 的默认构造函数是什么样的?
标签: c++ arrays dynamic indexing copy