【问题标题】:How to initialise const member variable of superclass in constructor of subclass in C++?如何在 C++ 子类的构造函数中初始化超类的 const 成员变量?
【发布时间】:2015-03-10 10:59:08
【问题描述】:

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

【问题讨论】:

    标签: c++ polymorphism list-initialization


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这里只能初始化一个类的成员变量和基类(不能初始化基类的成员)。

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

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

      Stain 像这样调用它:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-04
        • 1970-01-01
        • 1970-01-01
        • 2012-03-08
        • 1970-01-01
        • 2019-09-02
        • 2013-01-07
        相关资源
        最近更新 更多