- 全局变量,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;
// 声明全局变量 monster
extern int monster;
// 全局变量,表示怪物的初始血量
int monster = 10000;
// 定义英雄类 hero
class hero {
protected:
string name; // 英雄名字
int blood; // 英雄血量
int attack; // 英雄攻击力
public:
// 默认构造函数
hero() {}
// 带参构造函数,初始化英雄的名字、血量和攻击力
hero(string name, int hp, int attack) {
this->name = name;
this->blood = hp;
this->attack = attack;
}
// 虚成员函数,表示英雄进行攻击
virtual void Atk() =0;
};
// 定义法师类 mage,继承自英雄类 hero
class mage : public hero {
int ap_attack = 50; // 独有的法术攻击力
public:
// 默认构造函数
mage() {}
// 带参构造函数,初始化英雄的名字、血量、攻击力和法术攻击力
mage(string name, int hp, int attack, int ap_attack) : hero(name, hp, attack) {
this->ap_attack = ap_attack;
}
// 重写虚成员函数 Atk,加入法术攻击的逻辑
void Atk() {
monster -= (attack +ap_attack);
cout<<"法师攻击后怪物的血量:"<<monster<<endl;
}
};
// 定义射手类 shooter,继承自英雄类 hero
class shooter : public hero {
int ac_attack = 100; // 独有的高额物理攻击力
public:
// 默认构造函数
shooter() {}
// 带参构造函数,初始化英雄的名字、血量、攻击力和物理攻击力
shooter(string name, int hp, int attack, int ac_attack) : hero(name, hp, attack) {
this->ac_attack = ac_attack;
}
// 重写虚成员函数 Atk,加入高额物理攻击的逻辑
void Atk() {
monster -= (attack + ac_attack);
cout<<"射手攻击后怪物的血量:"<<monster<<endl;
}
};
int main() {
// 实例化法师和射手两个对象
mage m("Mage", 100, 20, 50);
shooter s("Shooter", 80, 30, 100);
// 循环攻击怪物,直到怪物的血量为 0
while(monster > 0){
m.Atk();
s.Atk();
}
cout << "Monster is killed!" << endl;
return 0;
}
结果: