静态字段是否继承?

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Prevent class inheritance in C++(防止 C++ 中的类继承)
Why should I declare a virtual destructor for an abstract class in C++?(为什么要在 C++ 中为抽象类声明虚拟析构函数?)
Why is Default constructor called in virtual inheritance?(为什么在虚拟继承中调用默认构造函数?)
C++ cast to derived class(C++ 转换为派生类)
C++ virtual function return type(C++虚函数返回类型)
Is there any real risk to deriving from the C++ STL containers?(从 C++ STL 容器派生是否有任何真正的风险?)