多态,纯虚函数与父子类继承

声明一个英雄类,成员属性:英雄名字、血量,定义成员函数攻击水晶(纯虚函数)

声明一个坦克类,继承自英雄类,新增属性:攻击力,重写攻击水晶函数,水晶下降血量为基础伤害(自定义)+坦克英雄攻击力

声明一个刺客类,继承自英雄类,新增属性:惩戒,重写攻击水晶函数,水晶下降血量为基础伤害(自定义)+惩戒量

定义全局函数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引用;所以并不适合定义静态变量,可以使用全局变量。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值