Are static variables in a base class shared by all derived classes?

前端 未结 7 1954
梦如初夏
梦如初夏 2020-11-28 04:56

If I have something like

class Base {
    static int staticVar;
}

class DerivedA : public Base {}
class DerivedB : public Base {}

Will bot

7条回答
  •  攒了一身酷
    2020-11-28 05:47

    The sample code given by @einpoklum is not working as it is because of the missing initialization of the static member foo_, missing inheritance in FooHolder declaration, and missing public keywords since we are dealing with classes. Here is the fixed version of it.

    #include 
    #include 
    
    class A {
    public:
        virtual const int& Foo() const = 0;
    };
    
    template 
    class FooHolder : public virtual A {
    public:
        const int& Foo() const override { return foo_; }
        static int foo_;
    };
    
    class B : public virtual A, public FooHolder { };
    class C : public virtual A, public FooHolder { };
    
    template<>
    int FooHolder::foo_(0);
    template<>
    int FooHolder::foo_(0);
    
    int main()
    {
      B b;
      C c;
      std::cout << b.Foo() << std::endl;
      std::cout << c.Foo() << std::endl;
    }
    

提交回复
热议问题