gpt4 book ai didi

c++ - 如何向现有类数组插入新值? (C++)

转载 作者:行者123 更新时间:2023-11-28 00:25:56 26 4
gpt4 key购买 nike

如果问题不够清楚,请见谅。我的 main 中有一个类数组,如下所示:

Character *character[100] = { new Player(001, 10, 5, "one", "type", "desc", "status", "knife", 10.0, 20.0, false, true, "Warrior", "M"),
new Enemies(200, 5, 0, "Snake", "Creep", "Normal Monsters", "Roaming", "None", 15.0, 23.4, true, true,"Poison"),
new Enemies(201, 7, 0, "Wolf", "Creep", "Normal Monsters", "Roaming", "None", 15.0, 23.4, true, true, "Bite"),
new Enemies(210, 7, 0, "Dragon", "Boss", "Dungeon Boss", "Idle", "None", 15.0, 23.4, false, false,"Flamethrower"),
new Enemies(*(Enemies*)character[1]),
new NPC(700,0,0,"Nero","NPC","Lobby NPC","Idle","None",0.0,0.0,false,false,"Lobby")};

在我的 addCharacter 函数中,我想在添加新角色之前先检查 ID 是否存在。所以假设我想添加一个新玩家。我想先检查玩家是否存在。我怎么做?这是我试过的代码。

cout << "=====================" << endl;
cout << "Add new player[" << count << "]" << endl;
cout << "=====================" << endl;
fflush(stdin);
cout << "Enter ID : ";
cin >> insert.ID;
for (int n = 0; n < 100; n++)
{
if (Player[n].getID() == insert.ID) //Error highlight under Player. Error:class "Character" has no member "Player"
{
cout << "ID already exists in index No." << n << " Please try again." << endl;
system("pause");
break; //Exit the function loop
}
}
cout << "Enter Level : ";
cin >> insert.Level;
cout << "Enter number of weapon(s) : ";
cin >> insert.NoOfWeapon;

最佳答案

Player 是您的类名。 character 是你的数组变量名。所以你应该测试。

if (character[n]->getID() == insert.ID)

但是,您的数组中的很多项都将包含 NULL 条目,因此您需要先检查一下。这样的事情会起作用。

if (character[n] != NULL && character[n]->getID() == insert.ID)

注意:使用 -> 从指针访问成员值(感谢 WhozCraig 指出这一点)。

关于c++ - 如何向现有类数组插入新值? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25110805/

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