Structs Inside Structs
A member can have any type: a number, a string, a vector, or another struct. A hero holds a weapon, and a weapon has a name and a damage of its own. So the weapon is a struct, and the hero has a member of that type:
struct Item {
std::string name;
int damage;
};
struct Hero {
std::string name;
int health;
Item weapon;
};Item has to be defined above Hero. The compiler reads the program from the top, and it must know Item when it gets to the member weapon; otherwise it reports unknown type name 'Item'. When you create the hero, the inner struct gets braces of its own:
Hero aria = {"Aria", 100, {"Dagger", 4}};To reach an inner member, chain the dots and read them from left to right. aria.weapon is a whole Item, so aria.weapon.name is its name:
#include <iostream>
#include <string>
struct Item {
std::string name;
int damage;
};
struct Hero {
std::string name;
int health;
Item weapon;
};
int main() {
Hero aria = {"Aria", 100, {"Dagger", 4}};
std::cout << aria.name << "'s weapon: " << aria.weapon.name << std::endl;
Item axe = {"Axe", 9};
aria.weapon = axe;
std::cout << aria.name << "'s weapon: " << aria.weapon.name << std::endl;
return 0;
}This prints:
Aria's weapon: Dagger
Aria's weapon: Axearia.weapon = axe; copies the whole item into the hero's hand, its name and its damage, as any assignment of a struct does.
When you skip a step in the chain, as in aria.damage, the compiler says that a Hero has no member damage. It's right: the damage belongs to the weapon, not to Aria.
main.cpp:17:53: error: no member named 'damage' in 'Hero'A member can be a vector too, such as the hero's bag: std::vector<Item> inventory;. When you create the hero with braces and leave it out, the inventory starts empty, and you add to it as to any vector: aria.inventory.push_back(axe);. Then aria.inventory.size() is the number of items, and aria.inventory[0].name the name of the first one.
Instructions
- 1
Print what Aria holds, with the name and the damage of her weapon read from the members:
Aria holds Dagger (damage 4). Keep the lines that create Aria and the sword as they are: the exercise will also try other weapons. - 2
Aria finds the sword. Below the line that prints her weapon, put the sword into her hand with one assignment, and print the same line again:
Aria holds Sword (damage 12). - 3
Aria keeps the dagger. Add a member
inventorytoHero, a vector of items, as its last member. Before Aria takes the sword, put her weapon into the inventory withpush_back. At the end ofmain, print the name of the first item in the inventory:In the inventory: Dagger.