gpt4 book ai didi

c++ - 传递数组时类中出现错误指针错误

转载 作者:行者123 更新时间:2023-11-28 06:32:50 25 4
gpt4 key购买 nike

所以我正在为游戏编写一个简单的战斗系统,但我在将一组指针传递给战斗系统类时遇到错误。

//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(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);

关于c++ - 传递数组时类中出现错误指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27230271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com