1.全局变量,int monster = 10000;定义英雄类hero,受保护的属性string name,int hp,int attck;公有的无参构造,有参构造,虚成员函数 void Atk(){monster-=0;},法师类继承自英雄类,私有属性 int ap_atk=50;重写虚成员函数void Atk(){monster-=(attck+ap_atk);};射手类继承自英雄类,私有属性 int ac_atk = 100;重写虚成员函数void Atk(){monster-=(attck+ac_atk);}实例化类对象,判断怪物何时被杀死。
#include <iostream>
using namespace std;
int monster=1000;//怪物的血量
class hero
{
protected:
string name;
int hp;//英雄的血量
int attack;//基础攻击力
public:
hero(){}
hero(string name,int hp,int attack):name(name),hp(hp),attack(attack)
{
cout<<"hero的有参构造"<<endl;
}
virtual void Atk()
{
monster-=0;
}
virtual ~hero()
{
cout<<"hero的析构函数"<<endl;
}
};
//法师
class Master:public hero
{
int ap_atk=50;//额外攻击力
public:
Master(){}
Master(string name,int hp,int attack):hero(name,hp,attack)
{
cout<<"Master的有参构造\t"<<name<<endl;
}
void Atk()
{
monster-=(attack+ap_atk);
cout<<"法师伤害\t"<<(attack+ap_atk)<<endl;
}
~Master()
{
cout<<"Master的析构函数"<<endl;
}
};
//射手
class Shooter:public hero
{
int ac_atk=100;
public:
Shooter(){}
Shooter(string name,int hp,int attack):hero(name,hp,attack)
{
cout<<"Shooter的有参构造\t"<<name<<endl;
}
void Atk()
{
monster-=(attack+ac_atk);
cout<<"射手伤害\t"<<(attack+ac_atk)<<endl;
}
~Shooter()
{
cout<<"Shooter的析构函数"<<endl;
}
};
//全局函数
void fun(hero &person)
{
person.Atk();
}
int main()
{
cout<<"法师初始化"<<endl;
Master A("蚩尤",110,40);
cout<<endl<<"射手初始化"<<endl;
Shooter B("东风",100,70);
int i=0;
cout<<endl;
while(monster>=0)
{
fun(A);
fun(B);
cout<<"怪物的剩余血量=\t"<<monster<<endl<<endl;
i++;
}
cout<<endl;
cout<<"攻击次数i=\t"<<i<<endl<<endl;
return 0;
}
2.思维导图