簡體   English   中英

重寫 C++ 中的 static 方法

[英]overriding static methods in C++

我有一個基礎 class Character ,它可以Attack()和派生類Magician (10)、 Elf (5) 或Giant (15)。 魔術師可以進化為BlackMagician (15)

每種類型的Character都有定義的Power (在括號中)。 我的問題是如何將 class 與 static function 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; }
};

我認為您可能將 static 與 const 混淆了。

私有:const int power = 10; // 在基數 class 中默認值為 10

//虛擬化並覆蓋 Power function 以返回 const int 值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM