繁体   English   中英

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

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

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

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

您必须为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_) {}
};

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

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

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

然后Stain像这样调用它:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM