gpt4 book ai didi

c++ - 在C++中重写静态方法

转载 作者:行者123 更新时间:2023-12-03 07:15:25 29 4
gpt4 key购买 nike

我有一个基类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,因为它没有可从中访问vtable的this实例指针。因此,每个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; }
};

关于c++ - 在C++中重写静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64668525/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com