静态字段是否继承?

96 c++ inheritance static

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

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;
}
Run Code Online (Sandbox Code Playgroud)

在所有三个实例中总共为3,或者它是2 SomeClass和1为1 SomeDerivedClass

e.J*_*mes 93

在所有情况下答案实际上是四个,因为构造SomeDerivedClass将导致总数增加两倍.

这是一个完整的程序(我用它来验证我的答案):

#include <iostream>
#include <string>

using namespace std;

class SomeClass
{
    public:
        SomeClass() {total++;}
        static int total;
        void Print(string n) { cout << n << ".total = " << total << endl; }
};

int SomeClass::total = 0;

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

int main(int argc, char ** argv)
{
    SomeClass A;
    SomeClass B;
    SomeDerivedClass C;

    A.Print("A");
    B.Print("B");
    C.Print("C");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

A.total = 4
B.total = 4
C.total = 4
Run Code Online (Sandbox Code Playgroud)


Ale*_*lli 50

3在所有情况下,由于static int total继承的SomeDerivedClass正好是一个SomeClass,而不是一个不同的变量.

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

编辑:第二个问题中的代码在int两种情况下均缺失,但添加它会使其正常,即:

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

class Cat: A
{
public:
    static const int MaxHP = 100;
};
Run Code Online (Sandbox Code Playgroud)

A :: MaxHP和Cat :: MaxHP的工作正常并且具有不同的值 - 在这种情况下,子类"不继承"来自基类的静态,因为,可以说,它用自己的同义词"隐藏"它一.

  • 很好的解释,但数字答案实际上是4,而不是3.看我的答案(http://stackoverflow.com/questions/998247/are-static-members-inherited-c/998298#998298) (9认同)
  • +1,很好,我正在编辑答案以指向您的答案,谢谢! (3认同)

小智 8

它是4,因为在创建派生对象时,派生类构造函数会调用基类构造函数.
因此静态变量的值递增两次.


小智 5

#include<iostream>
using namespace std;

class A
{
public:
    A(){total++; cout << "A() total = "<< total << endl;}
    static int total;
};

int A::total = 0;

class B: public A
{
public:
    B(){total++; cout << "B() total = " << total << endl;}
};

int main()
{
    A a1;
    A a2;
    B b1;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这将是:

A() total = 1
A() total = 2
A() total = 3
B() total = 4
Run Code Online (Sandbox Code Playgroud)