2.全局变量,int monster = 10000;定义英雄类hero,受保护的属性string name,int hp,int attck;公有的无参构造,有参构造,虚成员函数 void Atk(){blood-=0;},法师类继承自英雄类,私有属性 int ap_atk=50;重写虚成员函数void Atk(){blood-=(attck-ap_atk);};射手类继承自英雄泪,私有属性 int ac_atk = 100;实例化类对象,判断怪物何时被杀死。
#include <iostream>
using namespace std;
int monster = 10000;
class Hero
{
protected:
string name;
int hp;
int attck;
public:
Hero(){}
Hero(string name,int hp,int attck):name(name),hp(hp),attck(attck)
{}
virtual void Atk()
{
monster-=0;
}
};
class Caster:public Hero
{
int ap_atk=50;
public:
Caster(){}
Caster(string name, int hp, int attack):Hero(name, hp, attack) {}
void atk()
{
monster-=(attck+ap_atk);
}
};
class Archer:public Hero
{
int ad_atk = 100;
public:
Archer() {}
Archer(string name, int hp, int attack):Hero(name, hp, attack) {}
void atk()
{
monster -= (attck + ad_atk);
}
};
int main()
{
while(1)
{
Caster h1("A", 20000, 300);
h1.atk();//攻击
if (monster <= 0)
{
cout << "怪物已阵亡" << endl;
break;
}
cout << "A发动了攻击,怪物剩余血量" << monster << endl;
Archer h2("B", 12000, 400);
h2.atk();
if (monster <= 0)
{
cout << "怪物已阵亡" << endl;
break;
}
cout << "B发动了攻击,怪物剩余血量" << monster << endl;
}
return 0;
}