我在将值输入到放在类中的数组时遇到问题。我尝试通过使用方法来做到这一点。我的代码如下所示:
#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;
}
我想在“英雄”中加入“剑”,“盔甲”和“药水”等物品,但我还没有办法在“英雄”中编写方法,这样我就可以这样做。我可以通过将其字段公开直接加载它们,但我读到它不推荐。
答案 0 :(得分:0)
不要在Hero
课程中使用大小为20的数组,而是尝试使用std::vector
。如果你有addItem
Hero
方法,你可以简单地检查一下英雄是否可以持有任何项目(检查inventory.size()
对你创建的某个常量,可能类似于{ {1}})。
这样的事情:
MAX_INVENTORY_SIZE
答案 1 :(得分:0)
您需要为您的项目编写一个存取方法:
class Hero
{
private:
std::string name;
std::array<Item, 20> inventory; // use the array container instead of C-style arrays
unsigned int itemCount;
public:
Hero() : itemCount(0) {}
Hero(string n) : name(n), itemCount(0) {}
//returns the name of the hero
string getName()
{
return name;
}
//sets the name for the hero
void setName(const std::string& name)
{
this->name = name;
}
const Item& getItem(int i) const { return inventory[i]; } // NOTE: you may want some bounds checking here, but this is basically what you are doing
Item& getItem(int i) { return inventory[i]; } // to update a particular item
void addItem(const Item& item) { inventory[itemCount++] = i; } // same with bounds checking here
};