是否继承了静态字段? [英] Are static fields inherited?

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

问题描述

当静态成员被继承时,它们对于整个层次结构是静态的,或者只是那个类,即:

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, code> SomeClass 和1为 SomeDerivedClass

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

推荐答案

3在所有情况下,因为 SomeDerivedClass 继承的 static int total SomeClass ,不是一个不同的变量。

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

作为@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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆