I'm starting C : I was trying to make my "player1" attack my "player2", to make him remove health to my "player2" and finally to display the health of "player2". But it's not working and I can't find the mistake. Here's my code I hope you will be able to help me:
PLAYER.CPP
class Player {
public:
std::string pseudo;
int healthValue = 100;
int attackValue = 5;
Player(std::string aPseudo) {
pseudo = aPseudo;
healthValue = healthValue;
attackValue = attackValue;
}
std::string getPseudo() {
return pseudo;
}
int getHealthValue() {
return healthValue;
}
int getAttackValue() {
return attackValue;
}
void attack(Player aTargetPlayer) {
aTargetPlayer.healthValue -= this->attackValue;
}
};
MAIN.CPP
#include "Player.cpp"
int main() {
Player player1("player1");
Player player2("player2");
std::cout << player2.getHealthValue() << std::endl;
player1.attack(player2);
std::cout << player2.getHealthValue() << std::endl;
return 0;
}
CodePudding user response:
Here:
void attack(Player aTargetPlayer) {
aTargetPlayer.healthValue -= this->attackValue;
}
The parameter aTargetPlayer
is passed by value, this means you decreased the health of a copy, not the original one. You must pass by reference, like this:
void attack(Player &aTargetPlayer) {
aTargetPlayer.healthValue -= this->attackValue;
}
CodePudding user response:
@JuanR's answer is valid. Note also that, they way you designed your class, the attack()
method could very well be moved out of the class:
Why?
- The attacker does not have a stronger affinity to the code of the method than the attacked player. If anything, and since right now, the attack only affects the stats of the attacked player, you might have written a
getAttackedBy(const Player& other_player)
... - The code for
attack()
does not need access to protected or private members of thePlayer
class.
So consider writing:
void attack(Player& attacker, Player& attacked);
(This has both players passed by non-const reference in case you want to reduce the number of actions of the attacker, or allow it to take damage from the attacked player's defense etc.)