Structs and Functions
You can pass a whole struct to a function. Instead of three parameters for a monster's name, health and attack, the function gets one monster. Choose the kind of parameter as you learned in the lesson on references:
- A function that only reads the struct gets a const reference,
const Monster& monster. The struct isn't copied, and the function can't change it by mistake. - A function that changes the struct gets a reference,
Monster& monster.
#include <iostream>
#include <string>
struct Monster {
std::string name;
int health;
int attack;
};
// Prints the monster on one line
void printMonster(const Monster& monster) {
std::cout << monster.name << ": health " << monster.health << std::endl;
}
// Makes the monster stronger
void levelUp(Monster& monster) {
monster.health += 10;
monster.attack += 2;
}
int main() {
Monster orc = {"Orc", 50, 8};
printMonster(orc);
levelUp(orc);
levelUp(orc);
printMonster(orc);
return 0;
}This prints:
Orc: health 50
Orc: health 70The struct's definition must be above the functions, because they use the type. That's why a program starts with its types, right below the #include lines, then come the functions, and main is at the bottom.
Without the &, void levelUp(Monster monster) gets a copy of the orc. It makes the copy stronger, the copy disappears when the function ends, and the program prints Orc: health 50 twice, without any error. When a function "does nothing" to your struct, check the & first.
A function can take several structs, and each parameter gets the kind it needs. In the task, the hero buys an item in a shop. The function changes the hero's gold, so the hero is a Hero&. It only reads the item's price, so the item is a const Item&.
Instructions
- 1
In place of the first comment, write a function
void printHero(const Hero& hero)that prints the hero on one line, such asAria: health 100, gold 60. Call it at the end ofmain(beforereturn 0;). Keep the lines that create Aria and the items as they are: the exercise will also try other values. - 2
In place of the second comment, write a function
void buy(Hero& hero, const Item& item)that takes the item's price from the hero's gold. Inmain, below the call ofprintHero, let Aria buy the potion, and then callprintHero(aria)again. The program printsAria: health 100, gold 60and thenAria: health 100, gold 45. - 3
Aria can't buy what she can't pay for. Change
buy: when the hero has less gold than the item costs, the function changes nothing and printsNot enough gold for Sword., with the item's name. At the end ofmain, let Aria buy the sword, and print her again. The last two lines areNot enough gold for Sword.andAria: health 100, gold 45.