1. 整理思维导图
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;重写虚成员函数void Atk(){blood-=(attck+ac_atk);}实例化类对象,判断怪物何时被杀死。(能写多少写多少)
代码
#include <iostream>
using namespace std;
int blood =10000;
class Hero
{
protected:
string name;
int attck;
public:
//constructor without param
Hero(){}
//constructor with param
Hero(string name, int attck):name(name), attck(attck)
{}
virtual void atk()
{
cout << "Hero attck" <<endl;
blood -= 0;
}
};
class Mage: public Hero
{
int ap_atk=50;
public:
Mage(string name, int attck):Hero(name, attck)
{
cout << "Mage constructor with 4 params" <<endl;
}
void atk()
{
cout << "Mage attck" <<endl;
blood -=(attck + ap_atk);
}
};
class Archer: public Hero
{
int ac_atk=100;
public:
Archer(string name, int attck):Hero(name, attck)
{
cout << "Archer constructor with 4 params" <<endl;
}
void atk()
{
cout << "Archer attck" <<endl;
blood -= attck+ac_atk;
}
};
int main()
{
Mage mage("Tang seng", 100);
Archer archer("Wu kong", 200);
Hero *pm = &mage; //parent point -->child
Hero *pa = &archer; //parent point -->child
int count_m = 0;
int count_a = 0;
while(1)
{
pm->atk();
count_m++;
if(blood <=0)
{
break;
}
pa->atk();
count_a++;
if(blood <=0)
{
break;
}
}
cout << "Mage attck = "<<count_m <<endl;
cout << "Archer attck = "<<count_a <<endl;
return 0;
}
运行结果