【问题标题】:Change the order of constructors in inheritance更改继承中构造函数的顺序
【发布时间】:2017-05-13 21:34:52
【问题描述】:

我正在为类继承构造顺序而苦苦挣扎。假设我有这两个类:

class A {
public:
    const int CONSTANT_A;
    A(const int constant) : CONSTANT_A(constant) {
    }
    void write() {
        std::cout << CONSTANT_A;
    }
};


class B : public A {
public:
    const int CONSTANT_B = 3;
    B() :A(CONSTANT_B) {
        write();
    }
};

当一个新对象B被创建时,CONSTANT_A不是3,因为类继承constructors order的工作原理如下:

  • 构造总是从基类开始。如果有多个基类,则从最左边的基类开始。
  • 然后轮到成员字段。它们按照声明的顺序进行初始化。
  • 最后构建了类本身。
  • 析构函数的顺序正好相反。

有没有办法强制成员常量首先初始化?哪种方法最干净?

【问题讨论】:

  • B() : A(3), CONSTANT_B(3) {} 将确保成员按预期进行初始化。不过,没有办法让 CONSTANT_BAs 构造函数之前初始化。

标签: c++ inheritance


【解决方案1】:

您的常量B::CONSTANT_B 可以是static,因为它不依赖于构造函数参数。

statics 在你的类对象被构造之前被初始化(除非它们也是static!)。

struct B : A
{
    static const int CONSTANT_B = 3;

    B() : A(CONSTANT_B)
    {
        write();
    }
};

如果B::CONSTANT_B 本身从构造函数参数中获取其值,您可能必须在ctor-member-initialiser 中将该参数命名两次。据我所知,没有任何简单的解决方法。

struct B : A
{
    const int CONSTANT_B;

    B(const int constant)
       : A(constant)
       , CONSTANT_B(constant)
    {
        write();
    }
};

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 2011-11-24
  • 2015-02-11
  • 1970-01-01
  • 2019-10-11
相关资源
最近更新 更多