【问题标题】:C++ I'm having some problems with arrays/dynamic memoryC++ 我在数组/动态内存方面遇到了一些问题
【发布时间】: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


【解决方案1】:

乍一看,特别是在你说你认为错误的地方,它可能在树的复制构造函数的实现中。我不知道“障碍”到底是什么,也不知道这 4 个实例的具体特征是什么。也许树实例有某种不能干净复制的数据,而其他 3 个则可以。

如果你不确定我所说的复制构造函数是什么意思,这可能是一件值得学习的事情。

http://en.wikipedia.org/wiki/Copy_constructor

【讨论】:

  • 所有障碍物都是相同的,除了它们的精灵。我尝试在第一个位置使用不同的障碍物,我使用哪个并不重要。但是,是的,昨天是我第一次听说复制构造函数(在阅读 3 规则时),但我并不太明白。看起来这将是我会更多研究的东西
猜你喜欢
  • 1970-01-01
  • 2021-12-12
  • 2021-11-29
  • 1970-01-01
  • 2017-08-30
  • 2023-03-27
  • 2021-07-06
  • 1970-01-01
  • 2022-11-23
相关资源
最近更新 更多