如何在C++中的子类的构造函数中初始化超类的const成员变量?

How to initialise const member variable of superclass in constructor of subclass in C++?

我有以下情况,我声明了一个 超类 const 成员,现在我想在其中一个 [=] 的构造函数中初始化它20=]子类使用列表初始化器

struct Shape {
public:
    const Rect boundingRect; // the rect in which the shape is contained
};

struct Stain : Shape
{
public:
    Stain(Rect boundingRect_) : boundingRect(boundingRect_) {}
};

我不确定这是否可行,如果我采用上面显示的直接方法,编译器会报错并显示以下消息:

member initializer 'boundingRect' does not name a non-static data member or base class

This answer 解释了为什么无法在 子类的 构造函数的 list initiliazers 中初始化超类的成员变量。我想知道针对这种情况的最佳做法是什么?

你只能在这里初始化class的成员变量和基础classes(不是基础class的成员)。

解决方案是给 Shape 一个接受初始化器的构造函数,例如:

Shape(Rect rect): boundingRect(rect) {}

Stain 像这样调用它:

Stain(Rect boundingRect_): Shape(boundingRect_) {}

如果您不想使用此构造函数进行通用 public,您可以将其设为 protected:

您必须为 struct Shape 添加一个构造函数并从您的子 class 调用它。像这样:

struct Shape {
public:
    const Rect boundingRect; // the rect in which the shape is contained

    Shape( Rect rect ) : boundingRecT( rect ) {}
};

struct Stain : Shape
{
public:
    Stain(Rect boundingRect_) : Shape (boundingRect_) {}
};