gpt4 book ai didi

c++ - 显示结构/类错误数组 C++

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

因此,我有一个包含名称、生命值和攻击力的英雄结构。我允许用户输入他们想要创建的英雄数量,并创建一个包含那么多英雄的数组(我在允许用户确定数组大小方面也遇到了问题,所以问题可能就在那里)。尝试使用数组循环设置属性时,出现错误:IntelliSense:没有运算符“[]”匹配这些操作数。操作数类型有:Hero [ int ]

我的问题是,如何循环遍历一个结构数组来设置它们的属性,如果是这样,显示英雄的信息是否与显示函数类似?

struct Hero
{
private:
string hName;
int hHealth;
int hAttack;

public:
void displayHeroData();
void setName(string);
void setHealth(int);
void setAttack(int);
};

void Hero::displayHeroData()
{
cout << "\n\n\n\nHERO INFO:\n" << endl;
cout << "Name: " << hName << endl;
cout << "Health: " << hHealth << endl;
cout << "Attack: " << hAttack << endl;
};

void Hero::setName(string name)
{
hName = name;
}

void Hero::setHealth(int health)
{
if(health > 0)
hHealth = health;
else
hHealth = 100;
}

void Hero::setAttack(int attack)
{
if(attack > 0)
hAttack = attack;
else
hAttack = 100;
}

int main()
{
string name;
int health;
int attack;
int num;
Hero *heroList; //declaring array

//getting size of array
cout << "How many hero's do you want to create? (greater than 0)" <<endl;
cin >> num;
heroList = new Hero[num]; //this is the array of Heroes

//looping through the array
for(int x = 0; x < num; ++x){

//creating a new hero, I think???
Hero heroList[x];

//setting hero's name
cout << "What is hero" << x <<"'s name?" << endl;
cin >> name;
heroList[x].setName(name);

//display the character after attributes have been set
heroList[x].displayCharacterData();

}//end of for loop


return 0;
}

最佳答案

Hero heroList[x];

永久删除此行。没必要。

关于c++ - 显示结构/类错误数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20035753/

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