Weapon 类:
- 私有成员(攻击力),
- set get 方法,
- 多态 equip 函数
Sword 类:继承Weapon 类,
- 属性(生命值),
- set get 方法
Blade类:继承Weapon 类,
- 属性(速度),
- set get 方法
Hero类:
- 私有成员(攻击,防御,速度,生命值),
- set get 方法,
- equipWeapon(Weapon* w)公开函数
实现:英雄装备Sword、Blade,属性加成不同
// 武器 基类
class Weapon {
private:
int attack; // 攻击力
public:
Weapon(int attack = 0) : attack(attack) {}
void setAttack(int attack) { this->attack = attack; }
int getAttack() const { return attack; }
// 多态函数:装备武器
virtual void equip(int& heroAttack,int& heroSpeed, int& heroHealth) const {
heroAttack += attack; // 默认只增加攻击力
}
};
class Sword : public Weapon {
private:
int healthBonus; // 生命值加成
public:
Sword(int attack = 0, int healthBonus = 0) : Weapon(attack), healthBonus(healthBonus) {}
// 设置生命值加成
void setHealthBonus(int healthBonus) { this->healthBonus = healthBonus; }
int getHealthBonus() const { return healthBonus; }
// 重写
void equip(int& heroAttack,int& heroSpeed, int& heroHealth) const override {
Weapon::equip(heroAttack,heroSpeed, heroHealth); // 基类的 equip
heroHealth += healthBonus; // 增加生命值
}
};
class Blade : public Weapon {
private:
int speedBonus; // 速度加成
public:
Blade(int attack = 0, int speedBonus = 0) : Weapon(attack), speedBonus(speedBonus) {}
// 设置速度加成
void setSpeedBonus(int speedBonus) { this->speedBonus = speedBonus; }
int getSpeedBonus() const { return speedBonus; }
// 重写
void equip(int& heroAttack,int& heroSpeed, int& heroHealth) const override {
Weapon::equip(heroAttack,heroSpeed, heroHealth);
heroSpeed += speedBonus; // 增加速度
}
};
// 英雄类
class Hero {
private:
int attack; // 攻击
int speed; // 速度
int health; // 生命值
public:
Hero(int attack = 0,int speed = 0, int health = 0)
: attack(attack),speed(speed), health(health) {}
// 设置攻击
void setAttack(int attack) {this->attack = attack; }
int getAttack() const {return attack; }
// 设置速度
void setSpeed(int speed) { this->speed = speed; }
int getSpeed() const { return speed; }
// 设置生命值
void setHealth(int health) { this->health = health; }
int getHealth() const { return health; }
// 装备武器
void equipWeapon(Weapon* weapon) {
weapon->equip(attack,speed, health); // 武器的 equip 函数
}
// 显示属性
void showStats() const {
cout << "英雄属性: " << endl
<<"攻击: " << attack << endl
<< "速度: " << speed << endl
<< "生命值: " << health << endl;
}
};
int main() {
// 创建英雄
Hero hero(100,30, 500);
cout << "初始状态:" << endl;
hero.showStats();
// 创建武器
Sword sword(20, 100); // 长剑:攻击 +20,生命值 +100
Blade blade(15, 10); // 匕首:攻击 +15,速度 +10
hero.equipWeapon(&sword);
cout << "装备长剑后:" << endl;
hero.showStats();
hero.equipWeapon(&blade);
cout << "装备匕首后:" << endl;
hero.showStats();
return 0;
}