Are static fields inherited?

前端 未结 7 1199
孤街浪徒
孤街浪徒 2020-11-28 02:44

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

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


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 03:26

    #include
    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;
    }
    

    It would be:

    A() total = 1
    A() total = 2
    A() total = 3
    B() total = 4
    

提交回复
热议问题