C++ 我在数组/动态内存方面遇到了一些问题

C++ I'm having some problems with arrays/dynamic memory

本文关键字:遇到 问题 方面 内存 数组 动态 C++      更新时间:2023-10-16

所以我正在做一个蹩脚的小滑雪游戏(这就是我所有问题的内容),我遇到了一些问题。我有一个生物模型类,它有一个动态数组来存储该生物模型可能存在的障碍物(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]运行良好。

有人能指出这段代码中的错误吗?

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

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

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