问题描述
我有一个基类Character
,可以Attack()
,派生类Magician
(10),Elf
(5)或Giant
(15 )。
魔术师可以进化到BlackMagician
(15)
每种类型的Character
(在括号中)都有一个已定义的Power
。我的问题是如何将类与静态函数getFamilyPower()
关联并相应地重写它。
代码如下: https://codecollab.io/@sdudnic/warriors
想法如下:
class Character {
static int power;
public:
static int getPower() { return power; }
virtual int Attack(Character *other) { /*...*/ }
};
class Magician : public Character {
static int power = 10;
public:
static int getPower() {return power; }
};
class Elf : public Character {
static int power = 5;
public:
static int getPower() {return power; }
};
class Giant : public Character {
static int power = 15;
public:
static int getPower() {return power; }
};
解决方法
仅virtual
方法可以被覆盖。但是static
方法不能是virtual
,因为它没有this
实例指针可从中访问vtable。因此,每个Character
都需要一个非静态的virtual
方法来报告其当前功率水平,例如:
class Character
{
public:
int health = 100;
void Attack(Character *other) {
int myPower = Power();
int theirPower = other->Power();
if (theirPower > myPower)
health -= theirPower;
else if (theirPower < myPower)
other->health -= myPower;
}
virtual int Power() = 0;
virtual void Evolve() {}
};
class Magician : public Character
{
public:
bool isBlack = false;
int Power() override { return isBlack ? 15 : 10; }
void Evolve() override { isBlack = true; }
};
class Elf : public Character
{
public:
int Power() override { return 5; }
};
class Giant : public Character
{
public:
int Power() override { return 15; }
};