简体   繁体   English

重写 C++ 中的 static 方法

[英]overriding static methods in C++

I have a base class Character , that can Attack() , and derived classes Magician (10), Elf (5) or Giant (15).我有一个基础 class Character ,它可以Attack()和派生类Magician (10)、 Elf (5) 或Giant (15)。 Magicians can evolve to BlackMagician (15)魔术师可以进化为BlackMagician (15)

each type of Character has a defined Power (in parenthesis).每种类型的Character都有定义的Power (在括号中)。 My question is how to associate a class with a static function getFamilyPower() and overrride it, accordingly.我的问题是如何将 class 与 static function getFamilyPower()相关联并相应地覆盖它。

The code is below: https://codecollab.io/@sdudnic/warriors代码如下: https://codecollab.io/@sdudnic/warriors

The idea is the following:这个想法如下:

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; }
};

Only virtual methods can be overridden.只能覆盖virtual方法。 But a static method cannot be virtual , as it has no this instance pointer from which to access a vtable.但是static方法不能是virtual ,因为它没有可以从中访问 vtable 的this实例指针。 So each Character will need a non-static virtual method to report its current power level, eg:所以每个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; }
};

I think you may be confusing static for const.我认为您可能将 static 与 const 混淆了。

private: const int power = 10;私有:const int power = 10; // in base class for a default value of 10 // 在基数 class 中默认值为 10

//virtualize and override the Power function to the return the const int value. //虚拟化并覆盖 Power function 以返回 const int 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM