Sunday 15 June 2014

c++ - Access two instances -



c++ - Access two instances -

i want programme little game in c++.

i want write method "attack" sets states of figure after attack. have 2 instances player , enemy. class looks like:

class figure { private: string name; int hp; int strength; int defense; public: void attack(int xstrength) { // method gets input values of player , should calculate // , set new hp stats of enemy after attack, sort of hp = hp - (xstrength - defense); } };

but how can phone call methode? need programm separate methode gets srength value of instance?, because cant phone call instances way:

enemy.attack();

because need input strength of instance player. or can access 1 value of instance such like

enemy.attack(player->get_xstrength)

with method:

void get_strength() { homecoming stength };

if extend class figure more values like, resistance, level, status etc. must programme lot of , set methodes.

your method should instead be:

void attack(figure & target) { target.hp -= strength - target.defense; }

this way specify target figure attacks, , can give access attacked figure properties. can:

figure player, enemy; enemy.attack(player);

also note have have kind of method sets properties, private , not set in constructor, in class right there no way set values, meaning garbage memory representation, or @ best - zeroes, depending on compiler implementation.

last not least, might want check after target hp calculation see if figure still alive, i.e. if (target.hp <= 0) ... // "target" dead

c++ copy instances

No comments:

Post a Comment