微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在C ++中覆盖静态方法

如何解决在C ++中覆盖静态方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。