[英]Bad pointer error in class when passing array
因此,我正在為游戲編寫一個簡單的戰斗系統,並且在傳遞指向戰系統類的指針數組時遇到錯誤。
//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;
}
我認為我缺少明顯的東西,但是誰能分享一些智慧?
謝謝。
拋開有關裸露的指針和所有權的樣式問題,我相信你的意思是
// v-- array of pointers
BattleSystem::BattleSystem(Battler *plyr, Battler *enemies[], int numEnemies)
和
BattleSystem *btl = new BattleSystem(&player, foes, 3);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.