声明一个英雄类,成员属性:英雄名字、血量,定义成员函数攻击水晶(纯虚函数)
声明一个坦克类,继承自英雄类,新增属性:攻击力,重写攻击水晶函数,水晶下降血量为基础伤害(自定义)+坦克英雄攻击力
声明一个刺客类,继承自英雄类,新增属性:惩戒,重写攻击水晶函数,水晶下降血量为基础伤害(自定义)+惩戒量
定义全局函数fun,传入不同的英雄类对象,函数体内调用攻击水晶函数。
主测试文件中,完成相关函数的测试功能
main.c文件
#include <iostream>
#include "test.h"
using namespace std;
int main()
{
Tank t("项羽",8000,50);
Assassin a("李白",5000,70);
Hero *p1 = &t;
Hero *p2 = &a;
while(1)
{
if(fun(*p1) < 0)
{
p1->show();
break;
}
else if(fun(*p2) < 0)
{
p2->show();
break;
}
}
return 0;
}
.h文件
#ifndef TEST_H
#define TEST_H
#include<iostream>
using namespace std;
class Hero
{
public:
Hero() {}
Hero(string n,int h):name(n),health(h){}
virtual ~Hero() {}
virtual int harm() = 0;
virtual void show() = 0;
//static int blood;
protected:
string name;
int health;
int base_attack = 80;
};
class Tank:public Hero
{
public:
Tank() {}
Tank(string n,int h,int a):Hero(n,h),attack(a) {}
~Tank() {}
int harm();
void show();
friend int fun(Hero &h);
protected:
int attack;
};
class Assassin:public Hero
{
public:
Assassin() {}
Assassin(string n,int h,int d):Hero(n,h),dis(d){}
~Assassin() {}
int harm();
void show();
friend int fun(Hero &h);
protected:
int dis;
};
//int Hero::blood = 100000;
int fun(Hero &h);
#endif // TEST_H
.c文件
#include <iostream>
#include "test.h"
using namespace std;
int blood = 100000;
int Tank::harm()
{
return attack+base_attack;
}
void Tank::show()
{
cout<<name<<"击破水晶"<<endl;
}
int Assassin::harm()
{
return dis+base_attack;
}
void Assassin::show()
{
cout<<name<<"击破水晶"<<endl;
}
int fun(Hero &h)
{
//return h.blood = h.blood-h.harm();
return blood = blood-h.harm();
}
需要注意当分文件编译时,使用静态成员变量定义水晶血量作为类中成员的时候.h的类中与.c的fun函数文件都需要静态变量blood,静态变量无法跨文件用extern引用;所以并不适合定义静态变量,可以使用全局变量。