很抱歉,如果问题不够明确。我在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;
答案 0 :(得分:3)
Player
是您的班级名称。 character
是您的数组变量名称。所以你应该测试一下。
if (character[n]->getID() == insert.ID)
但是,你的很多数组都会有NULL条目,所以你需要先检查一下。这样的事情会起作用。
if (character[n] != NULL && character[n]->getID() == insert.ID)
注意:使用->
从指针访问成员值(感谢WhozCraig指出这一点)。