You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <iostream>
#include <string>
using std::cout, std::string, std::endl;
class Player
{
public: // 放了方便后续代码编写,暂时将基类数据设定为公有
string name;
int attack, defence, HP; // 进攻 防御 生命
public:
Player(string _name, int _attack, int _defence, int _HP)
: name{_name}, attack{_attack}, defence{_defence}, HP{_HP}
{
}
void pk(Player &p)
{
while (HP > 0)
{
hit(p);
if (p.HP <= 0)
{
std::cout << p.name << "死亡!\n";
return;
}
p.hit(*this);
}
std::cout << name << "死亡!\n";
}
virtual void hit(Player &p) // 设定虚函数的接口
{
}
};
class Demon : public Player
{
public:
using Player::Player;
void hit(Player &p)
{
p.HP -= attack - p.defence;
HP += attack - p.defence;
std::cout << name << "砍了" << p.name << "一刀,并吸了一口血\n";
}
};
class Angel : public Player
{
public:
using Player::Player;
void hit(Player &p)
{
p.HP -= attack - p.defence;
p.HP -= attack - p.defence;
std::cout << name << "砍了" << p.name << "两刀\n";
}
};
class Ghost : public Player
{
public:
using Player::Player;
virtual void hit(Player &p)
{
p.HP -= (attack - p.defence) * 1.5;
HP += (attack - p.defence) * 0.5;
std::cout << name << "砍了" << p.name << "一大刀,并吸了一小口血\n";
}
};
int main()
{
Angel a{"孙悟空", 100, 20, 1000};
Demon d{"牛魔王", 100, 20, 1000};
Ghost g{"白骨精", 100, 20, 1000};
a.pk(d);
// 改成a.pk(g)试试不同?
// 在本例当中无论从Player派生出多少新的类
// 只要遵守虚函数的规定在pk函数中都可以通过各自对象来调用各自的hit方法
// 充分体现了动态多态性的魅力
}