重写C++中的静态方法

ecr0jaav  于 2022-12-27  发布在  其他
关注(0)|答案(2)|浏览(258)

我有一个基类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; }
};
a8jjtwal

a8jjtwal1#

只有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; }
};
7hiiyaii

7hiiyaii2#

我想你可能把静态和常量搞混了。
私有:常数整数幂= 10;//在基类中,默认值为10
//虚拟化并重写Power函数以返回const int值。

相关问题