Summary
In this lesson, you learned that:
- A struct groups values that belong together, even of different types, into a new type. Its definition lists its members and ends with
};, the semicolon included:struct Monster { std::string name; int health; int attack; };. Names of your own types start with a capital letter. - You create a variable of the new type as any other,
Monster goblin;, and reach a member with a dot:goblin.health. A member works like an ordinary variable of its type. - Braces give all the members their values at once, in the order of the definition:
Monster goblin = {"Goblin", 30, 5};. A member you leave out gets its default value from the definition (int health = 100;), or else 0 or an empty string. - A whole struct can't be printed with
std::coutor compared with==. Work with its members. - Assigning a struct copies all its members, and changing the copy leaves the original as it was. A reference,
Monster& target = goblin;, is another name for the same struct. - A vector of structs holds a struct in each element:
std::vector<Monster> monsters = {{"Goblin", 30, 5}, {"Orc", 50, 8}};,monsters[1].name,monsters.push_back({"Bat", 8, 2});. for (const Monster& monster : monsters)reads the structs in a vector, andfor (Monster& monster : monsters)changes them.for (Monster monster : monsters)works with copies and changes nothing in the vector.- A function gets a struct as
const Monster&when it only reads it, and asMonster&when it changes it. A function can also return a struct:Monster makeMonster(const std::string& name, int level). - A member can be another struct or a vector, and you chain the dots:
aria.weapon.name,aria.inventory.push_back(axe);. - An enumeration,
enum class State { Exploring, Fighting, GameOver };, is a type with a fixed set of values. You write them asState::Fightingand compare them with==. To print one, turn it into a string with a function.
In the next lesson, Classes, your structs will get functions of their own, and you will decide which parts of a program may change their members.
Instructions
- 1
Let's practice. Write a function
printMonsterthat gets a monster as a const reference and prints its name, a health bar with one#for every 10 health, and the health:Goblin [###] 30. (std::string(3, '#')from the lesson on strings makes###.) Inmain, print every monster with it:Goblin [###] 30,Bat [#] 10,Orc [#####] 50andTroll [########] 80. Keep the lines of the vector as they are: the exercise will also try other monsters. - 2
An earthquake shakes the dungeon. Write a function
hitAllthat gets the vector of monsters and a damage, and takes the damage from every monster, but no monster's health goes below 0. Below the loop inmain, callhitAll(monsters, 25)and print every monster again. The last four lines areGoblin [] 5,Bat [] 0,Orc [##] 25andTroll [#####] 55. (Without the limit, the bat would have -15 health, andstd::string(-1, '#')would stop the program withstd::length_error: basic_string.)