所以我正在为游戏编写一个简单的战斗系统,并且我在向战斗系统类传递指针数组时出错。
//Create the player and 3 enemies
Battler player("Player", 100, 100, 50, 50, 50, 50, 90);
Battler foe1("Imp", 100, 100, 50, 50, 50, 50, 80);
Battler foe2("Ogre", 100, 100, 50, 50, 50, 50, 75);
Battler foe3("Giant", 100, 100, 50, 50, 50, 50, 60);
//Create an array of pointers that point to the enemies
Battler *foes[3];
foes[0] = &foe1;
foes[1] = &foe2;
foes[2] = &foe3;
//Initialize the battlesystem passing the player, the array of enemies
//and the number of enemies (3)
BattleSystem *btl = new BattleSystem(&player, *foes, 3);
所以这个工作正常,但是当我将数组传递给类时,第一个成员传递正常,但其余成员通过,当我执行断点时,它们被发送为" Badptr"
以下是battlesystem构造函数的代码:
BattleSystem::BattleSystem(Battler *plyr, Battler enemies[], int numEnemies)
{
player = plyr;
//foe is declared as Battler *foe; So it just points to the first member of the enemies
// array so I can access them. But only the first member gets a value the rest get
// "Bad ptr" with garbage values and when I look through the enemies array passed
// to the constructor, it has BAD PTRs in everything but the first element.
foe = enemies;
numFoes = numEnemies;
totalTurns = 0;
foeTurns = new int[numFoes];
turnList = new Battler*[numFoes + 1];
for(int i = 0; i <= numFoes; i++)
{
turnList[i] = &foe[i];
}
turnList[numFoes + 1] = player1;
}
我错过了一些我认为明显的东西,但任何人都可以分享一些智慧吗?
谢谢。
答案 0 :(得分:1)
暂不讨论关于裸指针和所有权的风格问题,我相信你的意思
// v-- array of pointers
BattleSystem::BattleSystem(Battler *plyr, Battler *enemies[], int numEnemies)
和
BattleSystem *btl = new BattleSystem(&player, foes, 3);