0
How can I permanently change a class's member?
I have a class, Hero, with a public health member and a takeHit function, like this: class Hero { public: Hero(int hp) : health(hp) { } int takeHit(int damage) { health = health - damage; return health; } }; int main() { Hero superhero(120); superhero.takeHit(20); cout << superhero.health << endl; return 0; } The problem is, the value returned by the function is correct, but when I cout superhero.health, it outputs the initial value of health. How can I permanently change the health member?
3 Antworten
+ 1
Sorry, I thought that example would behave the same way my real problem code does. Here is the code that's actually causing the problem
https://code.sololearn.com/c2596vrjm5c8/?ref=app
0
jacksonofgames 28 , with your code, I expected to health to be 100 (120-20) and it does print 100 when I checked on code playground.... what is issue I don't get... it is not printing initial value 120...
0
class Hero {
public:
int health;
Hero(int hp){
(*this).health=hp;
}
void takeHit(int damage) {
(*this).health = (*this).health - damage;
}
};
#include <iostream>
using namespace std;
int main() {
Hero superhero(120);
superhero.takeHit(20);
cout << superhero.health << endl;
return 0;
}
Changed it a bit, prints out 100 for me :P