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

时间:2015-03-10 10:59:09

标签: c++ polymorphism list-initialization

我有以下情况,我声明了超类const成员,现在我想在其子类的构造函数中初始化它>使用列表初始化程序

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 中初始化超类的成员变量。我想知道这种情况的最佳做法是什么?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

您只能在此处初始化类的成员变量和基类(而不是基类的成员)。

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

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

Stain像这样调用它:

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

如果您不希望普通公众使用此构造函数,则可以将其设为protected:

相关问题