0

我在将值输入到放置在类中的数组时遇到问题。我尝试通过使用方法来做到这一点。我的代码如下所示:

#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 中添加项目“剑”、“盔甲”和“药水”,但是我还没有找到在“英雄”中编写允许我这样做的方法的方法。我可以通过公开其字段来直接加载它们,但我读到不推荐这样做。

4

2 回答 2

0

尝试Hero使用std::vector. 如果你有一个addItem方法Hero,你可以简单地检查英雄是否可以持有更多物品(检查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);
于 2013-09-23T19:16:11.287 回答
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
};
于 2013-09-23T19:20:36.067 回答