多态 作业
Weapon 类:
- 私有成员(攻击力),
- set get 方法,
- 多态 equip 函数
Sword 类:继承Weapon 类,
- 属性(生命值),
- set get 方法
Blade类:继承Weapon 类,
- 属性(速度),
- set get 方法
Hero类:
- 私有成员(攻击,防御,速度,生命值),
- set get 方法,
- equipWeapon(Weapon* w)公开函数
实现:英雄装备Sword、Blade,属性加成不同
// 前向声明 Weapon 类
class Weapon;
// 英雄类
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); // 声明 equipWeapon 方法
// 显示属性
void showStats() const {
cout << "英雄属性: " << endl
<< "攻击: " << attack << endl
<< "速度: " << speed << endl
<< "生命值: " << health << endl;
}
};
// 武器基类
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(Hero& hero) const {
hero.setAttack(attack + hero.getAttack()); // 默认只增加攻击力
}
};
// Sword 类
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(Hero& hero) const override {
Weapon::equip(hero); // 基类的 equip
hero.setHealth(healthBonus + hero.getHealth()); // 增加生命值
}
};
// Blade 类
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(Hero& hero) const override {
Weapon::equip(hero); // 基类的 equip
hero.setSpeed(speedBonus + hero.getSpeed()); // 增加速度
}
};
// 实现 Hero 类的 equipWeapon 方法
void Hero::equipWeapon(Weapon* weapon) {
weapon->equip(*this); // 传递当前对象
}
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;
}