Quiz: Damage in a Loop
This program should take 10 health from each monster and then print 20 and 40, but it doesn't compile. Click the line with the mistake.
1#include <iostream>
2#include <string>
3#include <vector>
4
5class Monster {
6private:
7 std::string name;
8 int health;
9
10public:
11 Monster(std::string monsterName, int startHealth) {
12 name = monsterName;
13 health = startHealth;
14 }
15
16 void takeDamage(int amount) {
17 health -= amount;
18 }
19
20 int getHealth() const {
21 return health;
22 }
23};
24
25int main() {
26 std::vector<Monster> monsters = {Monster("Goblin", 30), Monster("Orc", 50)};
27 for (const Monster& monster : monsters) {
28 monster.takeDamage(10);
29 }
30 for (const Monster& monster : monsters) {
31 std::cout << monster.getHealth() << std::endl;
32 }
33 return 0;
34}