为什么不能在派生类的构造函数初始化列表中初始化基类的数据成员?

hu *_*ang 2 c++ inheritance constructor initializer-list

这就是代码,并带有错误:"非法成员初始化:'a'不是基础或成员",错误信息的含义是什么,为什么?

class A{
public:
int a;
};
class B:public A{

public:
B();
};

B::B():a(10){    // put  "a(10)" into the constructor body is right

}
Run Code Online (Sandbox Code Playgroud)

Dav*_*rtz 8

在调用派生类的构造函数时,必须已经构造了基类.所以现在已经太晚了.要了解为什么必须这样,请考虑:

class Base
{
    public:
    int i;
    Base(int q) : i(q) { ; }
};

class Middle : public Base
{
    public:
    Middle() : Base(2) { printf("i=%d\n", i); }
};

class Derived : public Middle
{
    public:
    Derived() : i(3) { ; }
}
Run Code Online (Sandbox Code Playgroud)

现在,想一想.该Middle构造有之前运行Derived的构造.并且Middle构造函数确保i为2.那么Derived构造函数后来如何使用不同的值重新构造它?