我在将值输入到放置在类中的数组时遇到问题。我尝试通过使用方法来做到这一点。我的代码如下所示:
#include <iostream>
using namespace std;
//class for items
class Item{
string name;
int amount;
public:
Item();
Item(string, int);
//returns the name of an item
string getName(){
return name;
}
//sets name for items
void setName(string name){
this->name = name;
}
//returns the amount of items
int getAmount(){
return amount;
}
//sets the amount for items
void setAmount(int amount){
this->amount = amount;
}
};
//first constructor
Item::Item(){
name="none";
amount=0;
}
//second constructor
Item::Item(string name, int amount){
this->name=name;
this->amount=amount;
}
//class for hero with "Items" array
class Hero{
string name;
Item inventory[20];
public:
Hero();
Hero(string);
//returns the name of the hero
string getName(){
return name;
}
//sets the name for the hero
void setName(string name){
this->name = name;
}
};
//first constructor
Hero::Hero(){
name="none";
}
//second constructor
Hero::Hero(string name){
this->name=name;
}
int main() {
Hero firsthero;
string name;
//giving hero the name
cout<<"Input name: ";
cin>>name;
firsthero.setName(name);
//printing the hero's name
cout<<firsthero.getName()<<endl;
//setting the items;
Item sword;
Item armor;
Item potion;
//setting items' values;
sword.setName("sword");
sword.setAmount(1);
armor.setName("armor");
armor.setAmount(1);
potion.setName("potion");
potion.setAmount(3);
//gives these items into array "inventory" in the "firsthero" class
return 0;
}
我想在 firsthero 中添加项目“剑”、“盔甲”和“药水”,但是我还没有找到在“英雄”中编写允许我这样做的方法的方法。我可以通过公开其字段来直接加载它们,但我读到不推荐这样做。