如何定义从结构继承的静态变量

How do I define a static variable inherited from a struct?

本文关键字:继承 结构 静态 变量 何定义 定义      更新时间:2023-10-16

我有一个头,里面有一个结构:

#ifndef CHARACTER_H_
#define CHARACTER_H_
#include <string>
using namespace std;
struct Character
{
    string name;
    static string type;
    static int baseHp, baseAttack, baseDefence;
};
#endif

我有一个继承该标头的类,我想在继承类的结构中定义静态变量。假设我的继承类如下:

#include "Character.h"
#include <string>
class Rouge: private Character
{
public:
    Rouge(string name)
    {
        this->name = name;
    }
    string getName()
    {
        return name;
    }
};

Rouge类中,我将在哪里定义Character标头中声明的静态变量,以及如何进行定义?

您将它们定义为Rouge不存在;他们是Character:的成员

string Character::type;
int    Character::baseHp;
int    Character::baseAttack;
int    Character::baseDefence;

因此,如果您期望从Character派生的每个类的这些值不同,那么您会感到失望:数据成员不能被"重写"。

相反,传统的做法是覆盖在基中声明但使成为纯虚拟的getter函数,这样Character就变为纯函数,Rouge必须覆盖这些函数,以便根据需要返回该特定类型的值。

实现固定值的一种简单方法是使用产生这些值的虚拟函数:

class Animal
{
public:
    virtual
    auto number_of_tails() const -> int { return 0; }
};
class Doggie
    : public Animal
{
public:
    auto number_of_tails() const -> int override { return 1; }
};

我希望我把override关键字放对了。

如果您希望这些信息在没有类实例的情况下可用,只需用静态函数实现即可:

class Doggie
    : public Animal
{
public:
    auto number_of_tails() const -> int override { return the_number_of_tails(); }
    static
    auto the_number_of_tails() const -> int { return 1; }
};

免责声明:编译器从未接触过代码。