+ 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;

19th Mar 2019, 8:42 AM
Clueless Coder
Clueless Coder - avatar
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; }
20th Mar 2019, 3:40 AM
Sonic
Sonic - avatar
+ 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 { };
19th Mar 2019, 10:54 AM
Hatsy Rei
Hatsy Rei - avatar
0
Code blocks не запускает консоль что делать?
28th Mar 2019, 3:32 PM
Дмитрий Гурульов
Дмитрий Гурульов - avatar
0
Дмитрий Гурульов, возможно у тебя там проблемы с компилятором или ты создавал НЕ консольный проэкт. Выберы при создании Console Application
2nd Apr 2019, 3:27 PM
Igor The Golden Fish
Igor The Golden Fish - avatar