#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <vector>
#include <memory>
using namespace std;
// 基类 Weapon
class Weapon {
protected:
int atk;
public:
Weapon(int atk = 0) : atk(atk) {}
virtual void setatk(const int& _atk) {
atk = _atk;
}
virtual int getatk() const { // 使用 const 保证不会修改成员
return atk;
}
virtual ~Weapon() = default; // 确保正确的析构
};
// 派生类 Sword (长剑)
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(){ // 重写 getatk 并返回属性
all[0] = atk;
all[1] = hp;
return all;
}
};
// 派生类 Blade (短剑)
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(){ // 重写 getatk 并返回属性
all[0] = atk;
all[1] = spd;
return all;
}
};
// 派生类 Axe (斧头)
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(){ // 重写 getatk 并返回属性
all[0] = atk;
all[1] = def;
return all;
}
};
// Hero 类,能够装备不同的武器,并获得不同的加成
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;
}