2

我有以下情况,我声明了一个超类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

这个答案解释了为什么不能在子类构造函数的列表初始化器中初始化超类的成员变量。我想知道这种情况的最佳做法是什么?

4

2 回答 2

4

您必须添加一个构造函数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_) {}
};
于 2015-03-10T11:07:56.710 回答
2

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

解决方案是提供Shape一个接受初始值设定项的构造函数,例如:

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

Stain像这样调用它:

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

如果您不希望公众使用此构造函数,您可以制作它protected:

于 2015-03-10T11:07:07.183 回答