C++ 多态的游戏例程
1)头文件 game.h
#ifndef GAME_H #define GAME_H // base class class CCreature { protected: int m_nLifePower, m_nPower; public: virtual void Attack(CCreature *pCreature){} virtual void Hurted(int nPower){} virtual void FightBack(CCreature *pCreature){} virtual int IsDead(){} }; class CDragon: public CCreature { public: CDragon(); virtual void Attack(CCreature *pCreature); virtual void Hurted(int nPower); virtual void FightBack(CCreature *pCreature); virtual int IsDead(); }; class CWolf: public CCreature { public: CWolf(); virtual void Attack(CCreature *pCreature); virtual void Hurted(int nPower); virtual void FightBack(CCreature *pCreature); virtual int IsDead(); }; #endif // GAME_H
2)成员函数实现文件game.cpp
#include <iostream> #include "game.h" using namespace std; // === Dragon CDragon::CDragon() { this->m_nLifePower = 100; // life value this->m_nPower = 50; // attack ability } void CDragon::Attack(CCreature *p) { // attack code place here cout << "Dragon fire" << endl; p->Hurted(m_nPower); if (!p->IsDead()) p->FightBack(this); } void CDragon::Hurted(int nPower) { // hurt action place here cout << "Dragon hurt " << nPower << endl; m_nLifePower -= nPower; if (m_nLifePower <= 0) cout << "Dragon was killed" << endl; } void CDragon::FightBack(CCreature *p) { // fight back action place here. cout << "Dragon fire back! " << endl; p->Hurted(m_nPower/2); } int CDragon::IsDead() { if (m_nLifePower <= 0) return 1; return 0; } // === Wolf CWolf::CWolf() { this->m_nLifePower = 80; // life value this->m_nPower = 30; // attack ability } void CWolf::Attack(CCreature *p) { // attack code place here cout << "CWolf palm" << endl; p->Hurted(m_nPower); if (!p->IsDead()) p->FightBack(this); } void CWolf::Hurted(int nPower) { // hurt action place here cout << "CWolf hurt " << nPower << endl; m_nLifePower -= nPower; if (m_nLifePower <= 0) cout << "CWolf was killed" << endl; } void CWolf::FightBack(CCreature *p) { // fight back action place here. cout << "CWolf palm back! " << endl; p->Hurted(m_nPower/2); } int CWolf::IsDead() { if (m_nLifePower <= 0) return 1; return 0; }
3)主程序文件 main.cpp
#include <iostream> #include <string.h> #include "game.h" using namespace std; int main() { CDragon dragon; CWolf wolf; while (1) { for (int i = 0; i < 60000; i++); dragon.Attack(&wolf); if (wolf.IsDead()) break; } return 0; }
4)运行结果