Recently I asked how to call variables in other classes. The answer revolved around setting the values and just retrieving that value. My question now revolves around global variables.
first.cpp
1 2 3 4 5 6 7
#include<iostream>
usingnamespace std;
externint initial;
int main(){
cout << "What is your first initial?" <<endl;
cin >> initial;
Im still having trouble using different classes and variables throughout. For example If I have a health variable in class pirate. I want to use an if statement if for the health variable in class monk. How would I go about that?
declare the same variable in the other class and initiate it to 0. now check its value, if the value is same as you entered through the code you shown then the variable exists otherwise not
// An interface
class Entity {
public:
virtual ~Entity() {}
virtualvoid getHP() const = 0; // Get the current HP of the entity
virtualvoid takeDamage(int dmg) = 0;
virtualvoid attack(Entity* other) = 0;
// other common functions
};
// Pirate class
class Pirate : public Entity {
public:
Pirate() : _hp(20) {}
virtual ~Pirate() {}
virtualvoid getHP() const override { return _hp; }
virtualvoid takeDamage(int dmg) { _hp -= dmg; }
virtualvoid attack(Entity* other) { other->takeDamage(5); }
protected:
int _hp;
};
// Monk class
class Monk : public Entity {
public:
Monk() : _hp(50) {}
virtual ~Monk() {}
virtualvoid getHP() const override { return _hp; }
virtualvoid takeDamage(int dmg) { _hp -= dmg; }
virtualvoid attack(Entity* other) { other->takeDamage(2); }
protected:
int _hp;
};
// ...
Entity* pirate = new Pirate;
Entity* monk = new Monk;
if (monk->getHP() < pirate->getHP()) {
// ...
}
Note that this is just an example - for doing what I have there, there are better ways (such as data orientation), but I'm just putting this around what you have said so far.