Objects as Parameters
A hero needs someone to fight. The monsters become a class too, with the same rule for health, and the hero gets a method that attacks a monster. Each class here has only the members this program needs:
#include <iostream>
#include <string>
class Monster {
private:
std::string name;
int health;
public:
Monster(std::string monsterName, int startHealth) {
name = monsterName;
health = startHealth;
}
void takeDamage(int amount) {
health -= amount;
if (health < 0) {
health = 0;
}
}
void printStatus() const {
std::cout << name << ": health " << health << std::endl;
}
};
class Hero {
private:
std::string name;
int attack;
public:
Hero(std::string heroName, int heroAttack) {
name = heroName;
attack = heroAttack;
}
void hit(Monster& target) {
target.takeDamage(attack);
}
};
int main() {
Hero aria("Aria", 12);
Monster goblin("Goblin", 30);
aria.hit(goblin);
aria.hit(goblin);
goblin.printStatus();
return 0;
}This prints:
Goblin: health 6The method hit gets the monster as a parameter, Monster& target, and calls the monster's method: target.takeDamage(attack). Here, attack is the hero's member, and target is the goblin from main. The parameter is a reference, for the same reason as with structs: without the &, target would be a copy, the hero would hit the copy, and the program would print Goblin: health 30, without any error.
hit can't touch the goblin's health directly. target.health -= attack; ends with the error 'health' is a private member of 'Monster'. Private means private to the class: only the methods of Monster can use its members, so even the hero has to go through takeDamage, and the rule about 0 holds.
The order of the classes matters, as with functions. Hero uses Monster, so Monster has to be above it. The other way round, compiling ends with unknown type name 'Monster'.
Instructions
- 1
This time, the monsters strike the hero, so
Herois the class above. Add to the classMonstera methodstrike(Hero& target), which takes the monster's attack from the target's health. At the end ofmain, the troll strikes Aria twice and the bat once. Then print her status again. The program printsAria: health 100and thenAria: health 60. Keep the lines that create Aria and the troll as they are: the exercise will also try other values. - 2
Then the troll keeps striking as long as Aria is alive. Write a
whileloop for it, count the strikes, and after the loop, printMore strikes: 4.