[英]Class type arrays in other classes in C++
我在将值输入到放置在类内部的数组中时遇到问题。 我尝试通过使用方法来做到这一点。 我的代码如下所示:
#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;
}
我想将“剑”,“装甲”和“药水”添加到第一英雄中,但是我还没有找到一种方法可以在“英雄”中编写方法。 我可以通过公开其字段直接加载它们,但我读到不建议这样做。
而不是在Hero
类中使用大小为20的数组,请尝试使用std::vector
。 如果您有Hero
的addItem
方法,则可以简单地检查一下英雄是否可以容纳更多物品(对照您创建的常量inventory.size()
例如MAX_INVENTORY_SIZE
) MAX_INVENTORY_SIZE
)。
所以像这样:
std::vector<Item> inventory;
const int MAX_INVENTORY_SIZE = 20;
...
//returns true if it successfully added the item, false otherwise
bool Hero::addItem(Item i) {
if(inventory.size < MAX_INVENTORY_SIZE) {
inventory.push_back(i);
return true;
}
return false;
}
...
hero.addItem(sword);
hero.addItem(armor);
hero.addItem(potion);
您需要为您的商品编写访问器方法:
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
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.