error C2614: 'ChildClass' : illegal member initialization: 'var1' is not a base or member

前端 未结 2 433
无人共我
无人共我 2020-12-31 07:20

I am getting the following error in C++:

error C2614: \'ChildClass\' : illegal member initialization: \'var1\' is not a base or member

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-31 07:54

    It doesn't work for the exact reason the error message provides you: you can only use initializer lists with direct members or base classes.

    In your case, you don't even need to initialize var1, since Base::Base() will be called by Child's constructor, which will set var1 to 0.

    If you want a different value, you'll have to overload Base constructor and call it explicitly:

    class Base 
    {
    protected:
         int var1;
    public:
         Base() : var1(0)
         {
         }
         Base(int x) : var1(x)
         {
         }
    };
    
    class Child:public Base
    {
        int chld;
    public: 
        Child(): Base(42) , chld(1)
        {
        }
    };
    

提交回复
热议问题