1) header file game.h
#ifndef Game_h#defineGame_h//base classclassCcreature {protected: intM_nlifepower, M_npower; Public: Virtual voidAttack (Ccreature *pcreature) {} Virtual voidHurted (intnpower) {} Virtual voidFightback (Ccreature *pcreature) {} Virtual intIsdead () {}};classCdragon: PublicCcreature { Public: Cdragon (); Virtual voidAttack (Ccreature *pcreature); Virtual voidHurted (intnpower); Virtual voidFightback (Ccreature *pcreature); Virtual intisdead ();};classCwolf: PublicCcreature { Public: Cwolf (); Virtual voidAttack (Ccreature *pcreature); Virtual voidHurted (intnpower); Virtual voidFightback (Ccreature *pcreature); Virtual intisdead ();};#endif //Game_h
2) member function implementation file Game.cpp
#include <iostream>#include"game.h"using namespacestd;//= = = DragonCdragon::cdragon () { This->m_nlifepower = -;//Life Value This->m_npower = -;//Attack Ability}voidCdragon::attack (Ccreature *p) { //Attack Code place herecout <<"Dragon Fire"<<Endl; P-hurted (M_npower); if(!p->isdead ()) P->fightback ( This);}voidCdragon::hurted (intnpower) { //hurt action place herecout <<"Dragon hurt"<< npower <<Endl; M_nlifepower-=npower; if(M_nlifepower <=0) cout<<"Dragon was killed"<<Endl;}voidCdragon::fightback (Ccreature *p) { //fight back action place here.cout <<"Dragon Fire back!"<<Endl; P->hurted (m_npower/2);}intCdragon::isdead () {if(M_nlifepower <=0) return 1; return 0;}//= = = WolfCwolf::cwolf () { This->m_nlifepower = the;//Life Value This->m_npower = -;//Attack Ability}voidCwolf::attack (Ccreature *p) { //Attack Code place herecout <<"Cwolf Palm"<<Endl; P-hurted (M_npower); if(!p->isdead ()) P->fightback ( This);}voidCwolf::hurted (intnpower) { //hurt action place herecout <<"Cwolf hurt"<< npower <<Endl; M_nlifepower-=npower; if(M_nlifepower <=0) cout<<"Cwolf was killed"<<Endl;}voidCwolf::fightback (Ccreature *p) { //fight back action place here.cout <<"Cwolf Palm back!"<<Endl; P->hurted (m_npower/2);}intCwolf::isdead () {if(M_nlifepower <=0) return 1; return 0;}
3) Main program file main.cpp
#include <iostream>#include<string.h>#include"game.h"using namespacestd;intMain () {Cdragon dragon; Cwolf Wolf; while(1) { for(inti =0; I <60000; i++); Dragon. Attack (&Wolf); if(Wolf.) Isdead ()) Break; } return 0;}
4) Running Results
C + + polymorphic game routines