简体   繁体   English

C ++ 14在类构造函数初始化列表中初始化继承的成员

[英]C++14 Initializing inherited member in class constructor initialization list

I have a base class 我有一个基础课

class A
{
    protected:

    int a;
};

And a class which is derived: 还有一个派生的类:

class B : public A
{

    B(int a_val)
        : a{a_val} // not allowed by compiler?
    {
    }
};

I can solve the problem by: 我可以通过以下方法解决问题:

    B(int a_val)
    {
        a = a_val;
    }

Is this "the solution", or can I do what I originally tried to do? 这是“解决方案”,还是可以做我最初尝试做的事情?

Of course, I could do this: 当然,我可以这样做:

    B(int a_val)
        : A(a_val)
    {
    }

and change class A 并改变class A

    A(int a_val)
        : a{a_val}
    {
    }

However this isn't really "better" in the context of what I am doing. 但是,就我正在做的事情而言,这并不是真正的“更好”。

In reply to an answer below (by swang): Can I therefore do this? 回答以下答复(由swang提出):我可以这样做吗?

B(int a_val)
    : A(), a{a_val}
{
}

When you do this: 执行此操作时:

class B : public A
{

    B(int a_val)
        : a{a_val} // not allowed by compiler?
    {
    }
};

You are trying to initialise a variable that doesn't belong to class B yet, so the right solution is 您正在尝试初始化不属于B类的变量,因此正确的解决方案是

B(int a_val)
   : A(a_val)
{
};

You can do this 你可以这样做

B(int a_val)
{
    a = a_val;
};

Because before a = a_val, the default construct of A has been called, and A::a has been default initialised. 因为在a = a_val之前,已调用A的默认构造,并且A :: a已默认初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM