+ 6
Public Variables in Classes C++
In this code I have somehow messed up the inheritance. How can my classes access public variables from other classes without it failing. Here is the code: #include <iostream> #include <cstdlib> class Hero{ public: int power; int health; }; class Enemy : public Hero{ public: std::string type; int power; int health; virtual void attack(){ player.health -= monster.power; } }; class Monster : public Enemy : public Hero{ }; int main(){ Hero player; Enemy monster; player.power = std::rand() % 70 - 10 + 1; player.health = std::rand() % 200 - 300 + 1; monster.health = std::rand() % 200 - 300 + 1; monster.power = std::rand() % 70 - 10 + 1; std::cout << "Player power: "; std::cout << player.power; return 0;
4 odpowiedzi
+ 8
Also it looks like the monster and player objects declared within main are not known within the attack() virtual function of the Enemy class. Perhaps you want to pass in a reference to a Hero object into it and use the this keyword?? As in:
virtual void attack(Hero &player) {
player.health -= this->power;
}
+ 10
( ͡° ͜ʖ ͡°) You are redeclaring variables power and health in your derived class. These variables will shadow the public variables in your base class.
class Hero{
public:
int power;
int health;
};
class Enemy : public Hero{
public:
std::string type;
virtual void attack(){
player.health -= monster.power;
}
};
class Monster : public Enemy { };
0
Code blocks не запускает консоль что делать?
0
Дмитрий Гурульов, возможно у тебя там проблемы с компилятором или ты создавал НЕ консольный проэкт. Выберы при создании Console Application