//CCharacter Typesstatic int CHAR_TYPE = 0;static int SOLD_TYPE = 1;static int MONS_TYPE = 2;//BASE Classclass CCharacter{public: int m_nType; CCharacter(int nType) : m_nType(nType){}};//Soldier child classclass CSoldier : public CCharacter{public: CSoldier() : CCharacter(SOLD_TYPE){} void Attack(){ printf("FREEZE! I AM A SOLDIER! I K33L J00 NOW!\n"); }};//Monster child classclass CMonster : public CCharacter{public: CMonster() : CCharacter(MONS_TYPE){} void Growl(){ printf("RAR! I AM A MONSTER! PREPARE TO DIE!\n"); }};//Growl if pChar is a Monsterbool Growl(CCharacter *pChar){ if(pChar->m_nType == MONS_TYPE){ CMonster *pMons = (CMonster*)pChar; pMons->Growl(); return true; } return false;}//Attack if pChar is a Soldierbool Attack(CCharacter *pChar){ if(pChar->m_nType == SOLD_TYPE){ CSoldier *pSold = (CSoldier *)pChar; pSold->Attack(); return true; } return false;}int main(int argc, char* argv[]){ CMonster m; CSoldier s; Attack(&m); Attack(&s); Growl(&m); Growl(&s); return 0;}
C++ Question
Somewhat longwinded, but here''s the basic idea
Thanks JonStelly. Your idea can address the problem, but for my program, this would result in hundreds or even thousands of comparisons in every frame. Anyway, thanks for your help.
Thanks you all. I think I would move all the public attributes of Soldier and Monster back to Character, and use virtual functions. This may be the easiest way to corrert my program.
Thanks you all. I think I would move all the public attributes of Soldier and Monster back to Character, and use virtual functions. This may be the easiest way to corrert my program.
Ok, I think I understand what you mean (I think ) BTW - you can access base class information from a derived class, but not the other way. You''ll want to use virtual functions to override functions:
class cBaseChar
{
public:
virtual void Attack() { cout << "ATTACK!"; }
};
class cHero : public cBaseChar
{
private:
long MySpecialData;
};
class cMonster : public cBaseChar
{
public:
void Attack() { cout << "GRRR!"; }
};
main()
{
cHero Hero;
cMonster Monster;
Hero.Attack();
Monster.Attack();
}
Jim Adams
Author "Programming Role-Playing Games with DirectX"
jimadams@att.net
class cBaseChar
{
public:
virtual void Attack() { cout << "ATTACK!"; }
};
class cHero : public cBaseChar
{
private:
long MySpecialData;
};
class cMonster : public cBaseChar
{
public:
void Attack() { cout << "GRRR!"; }
};
main()
{
cHero Hero;
cMonster Monster;
Hero.Attack();
Monster.Attack();
}
Jim Adams
Author "Programming Role-Playing Games with DirectX"
jimadams@att.net
Jim Adams, Author"Programming Role-Playing Games with DirectX""Advanced Animation with DirectX""Programming Role-Playing Games with DirectX, 2nd Edition"
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement