Your code logic is all over the place - you're not doing yourself any favors by making a class and then making it really hard to use.
In my eyes, a Character should have some statistics (HP, etc), and an attack function.
A Character shouldn't have three different HP's, and then different functions that create new characters so that it can pretend to direct a scene.
Let's keep it very basic for now.
Like I said, a Character should have HP. Let's do that then:
1 2 3 4 5 6 7 8
|
class Character {
int health = 100;
public :
int getHealth() { return health; }
void takeDamage(unsigned int damage) { health -= damage; }
};
|
First of all, I've elected to name the "HP" integer "health" instead.
I've also decided to name the class
Character
and not
character
. This is more of a stylistic thing - I prefer to capitalize class names.
The
int health
is
private
by default. I'm also taking advantage of a C++11 feature which allows me to initialize in-class types other than const static integral ones on the same line on which they are declared.
We have to public methods that deal with our health variable.
getHealth
simply returns the current health, and
takeDamage
subtracts the argument from the current health. The argument is an unsigned integer, because if it was signed, you could pass negative numbers to the function - effectively "healing" a character.
I also said that a character should be able to attack another character. Let's do that now:
1 2 3 4 5 6 7 8 9
|
class Character {
int health = 100;
public :
int getHealth() { return health; }
void takeDamage(unsigned int damage) { health -= damage; }
void attack(Character& enemy) { enemy.takeDamage(10); }
};
|
All I've done is added another function called
attack
. This function takes a Character by reference as an argument. When an object exists outside of a function, but you want to modify that object in that function, you can pass the object by reference (or pass a pointer). The name we've given our reference in this case ("enemy") is just an alias, a handle to the actual object that was passed into the function, which allows us to modify the original.
If we didn't pass by reference, and passed by value, we would be modifying a copy, and any changes made to the copy would not be reflected in the original object. Furthermore, the copy would cease to exist once the function terminates.
Right now, the
attack
method only subtracts ten from the enemy's health. It's just a placeholder value.
Finally, this is how you might use this class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
class Character {
int health = 100;
public :
int getHealth() { return health; }
void takeDamage(unsigned int damage) { health -= damage; }
void attack(Character& enemy) { enemy.takeDamage(10); }
};
int main() {
Character hero;
Character villain;
while (hero.getHealth() > 0 && villain.getHealth() > 0) {
hero.attack(villain);
villain.attack(hero);
}
return 0;
}
|