静态字段是否继承?

2021-12-17 00:00:00 inheritance static c++

当继承静态成员时,它们是整个层次结构的静态成员,还是该类的静态成员,即:

When static members are inherited, are they static for the entire hierarchy, or just that class, i.e.:

class SomeClass
{
public:
    SomeClass(){total++;}
    static int total;
};

class SomeDerivedClass: public SomeClass
{
public:
    SomeDerivedClass(){total++;}
};

int main()
{
    SomeClass A;
    SomeClass B;
    SomeDerivedClass C;
    return 0;
}

在所有三个实例中总共是 3,还是 SomeClass 是 2,SomeDerivedClass 是 1?

would total be 3 in all three instances, or would it be 2 for SomeClass and 1 for SomeDerivedClass?

推荐答案

3 在所有情况下,因为 SomeDerivedClass 继承的 static int total 正是 SomeDerivedClass 中的那个code>SomeClass,不是一个独特的变量.

3 in all cases, since the static int total inherited by SomeDerivedClass is exactly the one in SomeClass, not a distinct variable.

实际上 4 在所有情况下,正如@ejames 在他的回答中发现并指出的那样.

actually 4 in all cases, as @ejames spotted and pointed out in his answer, which see.

第二个问题中的代码在两种情况下都缺少 int,但添加它就可以了,即:

the code in the second question is missing the int in both cases, but adding it makes it OK, i.e.:

class A
{
public:
    static int MaxHP;
};
int A::MaxHP = 23;

class Cat: A
{
public:
    static const int MaxHP = 100;
};

工作正常,并且 A::MaxHP 和 Cat::MaxHP 的值不同――在这种情况下,子类不继承"基类的静态,因为,可以这么说,它隐藏"了它它自己的同名.

works fine and with different values for A::MaxHP and Cat::MaxHP -- in this case the subclass is "not inheriting" the static from the base class, since, so to speak, it's "hiding" it with its own homonymous one.

相关文章