I made the following code as practice with classes and objects. However, when I try to modify the value of int hp inside the takedam function, it doesn't change anything outside the function. What is the best/most efficient way to change this value? I'm willing to read up on stuff, so if you point me in the right direction I'll try to figure it out.
Code:#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> class zergling { char name[20]; int hp; int basedamage; public: zergling(int starthp, int dmg, char *label); //constructor declaration ~zergling() {}; //destructor declaration and definition. int attack(int damage, zergling target); int takedam(int dam); }; zergling::zergling(int starthp, int basedmg, char *label) //definition of the constructor. { strcpy(name,label); hp=starthp; basedamage=basedmg; } int zergling::attack(int damage, zergling target) { int dmgtot=rand()%3+target.basedamage; printf("\nabout to inflict %d damage on a zergling, named %s\n",dmgtot,target.name); target.takedam(dmgtot); } int zergling::takedam(int dam) { hp-=dam; printf("\na zergling named %s has taken %d dam, and now has %d hp left.\n",name,dam,hp); } int main() { srand(time(NULL)); //starting the RNG base. printf("\nThis is a game of chance.\n"); char name1[20]; char name2[20]; printf("Enter the name of player 1: "); scanf("%s",name1); printf("Enter the name of player 2: "); scanf("%s",name2); zergling z1(35,5,name1); zergling z2(35,5,name2); printf("\nLet the battle begin!\n\n"); while (1) { z1.attack(3,z2); sleep(1); //z2.attack(3,z1); //sleep(1); } }



LinkBack URL
About LinkBacks



My bad. 