静态字段是否继承?

Are static fields inherited?(静态字段是否继承?)

本文介绍了静态字段是否继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于静态字段是否继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:静态字段是否继承?

基础教程推荐