C++继承和多态学习思维导图及练习

继承

多态

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <vector>
#include <memory>
 
using namespace std;
 

class Weapon {
protected:
    int atk;
public:
    Weapon(int atk = 0) : atk(atk) {}
 
    virtual void setatk(const int& _atk) {
        atk = _atk;
    }
 
    virtual int getatk() const {  
        return atk;
    }
 
    virtual ~Weapon() = default;  
};
 

class Sword : public Weapon {
private:
    int hp;
    int all[2];
public:
    Sword(int atk, int hp = 0) : Weapon(atk), hp(hp) {}
 
    void getatk(const int& _atk, const int& _hp) {
        atk = _atk;  
        hp = _hp;
    }
 
    int* getatk(){  
        all[0] = atk;
        all[1] = hp;
        return all;
    }
};
 

class Blade : public Weapon {
private:
    int spd;
    int all[2];
public:
    Blade(int atk, int spd = 0) : Weapon(atk), spd(spd) {}
 
    void getatk(const int& _atk, const int& _spd) {
        atk = _atk;  
        spd = _spd;
    }
 
    int* getatk(){  
        all[0] = atk;
        all[1] = spd;
        return all;
    }
};
 

class Axe : public Weapon {
private:
    int def;
    int all[2];
public:
    Axe(int atk, int def = 0) : Weapon(atk), def(def) {}
 
    void getatk(const int& _atk, const int& _def) {
        atk = _atk;  
        def = _def;
    }
 
    int* getatk(){  
        all[0] = atk;
        all[1] = def;
        return all;
    }
};
 
class Hero {
private:
    int atk;
    int def;
    int spd;
    int hp;
    Weapon* weapon;  // 使用基类指针
 
public:
    Hero(int atk = 0, int def = 0, int spd = 0, int hp = 0)
        : atk(atk), def(def), spd(spd), hp(hp), weapon(nullptr) {}
 
    // 装备武器
    void equipWeapon(Weapon* p) {
        weapon = p;
        // 使用多态来获取武器的 atk
        if (weapon) {
            this->atk += weapon->getatk();  // 增加英雄的 atk
        }
    }
 
    void display() {
        cout << "Hero stats -> atk: " << atk << ", def: " << def
             << ", spd: " << spd << ", hp: " << hp << endl;
    }
};
 
int main() {
    // 创建不同的武器
    Sword sword(100, 100);
    Blade blade(70, 30);
    Axe axe(130, 40);
 
    // 创建 Hero 对象
    Hero hero(50, 30, 20, 100);
 
    // 装备武器
    hero.equipWeapon(&sword);  // 装备长剑
    hero.display();
 
    hero.equipWeapon(&blade);  // 装备短剑
    hero.display();
 
    hero.equipWeapon(&axe);  // 装备斧头
    hero.display();
 
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值