简体   繁体   中英

How can I store objects of derived classes within a data structure from which can be accessed attributes which the base class does not have?

I am making a game and have different types for different "items", and want some way of storing them in an inventory. The issue I've got is that once they get put in the inventory, I cannot access attributes which the base class does not possess. Here's an example:

class Item {
  public:
    std::string name;
    Item(std::string n) : name{n} {};
}

class Weapon : public Item {
  public:
    int damage;
    Weapon(std::string n, int dam) : damage{dam}, Item(n) {};
}

class Armour : public Item {
  public:
    int armour;
    Weapon(std::string n, int arm) : armour{arm}, Item(n) {};
}

Weapon sword("Longsword", "10");
Armour helmet("Iron Helmet", "5");

std::vector<Item*> inventory = {&sword, &helmet};

When the sword or helmet are retrieved from inventory the attributes damage and armour do not exist anymore.

I understand why this is and what is happening here - the objects are being sliced and all that is being stored is the Item class part, but is there a way to get around this? I've seen virtual functions but can't find anything similar for attributes.

I managed to solve this by storing the objects in the vector as type base class pointer Item* in this case, and creating virtual functions to retrieve the desired attributes:

class Item {
  public:
    std::string name;
    Item(std::string n) : name{n} {};
    virtual int getDamage() {return 0;}
    virtual int getArmour() {return armour;}
}

class Weapon : public Item {
  public:
    int damage;
    Weapon(std::string n, int dam) : damage{dam}, Item(n) {};
    virtual int getDamage() {return damage;}
}

class Armour : public Item {
  public:
    int armour;
    Weapon(std::string n, int arm) : armour{arm}, Item(n) {};
    virtual int getArmour() {return armour;}

}

Weapon sword("Longsword", "10");
Armour helmet("Iron Helmet", "5");

std::vector<Item*> inventory = {&sword, &helmet};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM