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

标签 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

}

最佳答案

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

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) { ; }
}

现在想想。 Middle 构造函数必须在 Derived 构造函数之前运行。 Middle 构造函数确保 i 为 2。那么 Derived 构造函数稍后如何用不同的值重新构造它?

关于c++ - 为什么不能在派生类的构造函数初始化列表中初始化基类的数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11838460/

相关文章:

c++ - try, throw , catch 二维数组不起作用

c++ - 在套接字编程中接收结构并写入文件

C# Visual Studio 需要引用基类 dll

c# - 如何强制派生类覆盖基类的枚举?

typescript 中的类构造函数类型?

JAVA使用构造函数创建每个类的两个具有完整数据的对象,但出现错误

c# - App构造函数和app.Onstartup有什么区别?

c++ - 具有自定义删除器的 Unique_ptr

c++ - 有没有办法用 clang 有效地编译已经预处理的文件?

python - Django - 用户继承了 IntegrityError