成员对象的构造函数调用顺序

Constructor invocation order for member objects

我有下面的 class 树,它有一个 class 叶子的成员对象。 Leaf 的构造需要来自 Tree (height_) 的参数。我可以为此编写一个初始化方法。但是我们是否知道构造函数的调用顺序,从而在构造Treeclass时满足构造成员对象的依赖关系? 换句话说,当成员对象的实例化存在依赖时,单独的初始化方法(针对成员对象)是唯一的出路吗? 下面是一个最小的代码,我在 Leaf 的构造函数的参数中加了一个问号来表示我的问题:

class Tree {
    private:
    float height_;
    Leaf leaf_(?);
    public:
    explicit Leaf(const std::istream& input);
};
void Tree::Tree(const std::istream& input){
    // read height_ from input
    ...
}
class Leaf {
    private:
    float height_fraction_;
    public:
    // height is required for construction of Leaf class
    Leaf(const float& height); 
};
void Leaf::Leaf(const float& height)
{
    height_fraction_ = 0.5*height; 
}

成员的构建按照声明的顺序进行。这对后面的来说非常重要。如果声明的顺序与依赖项的使用顺序不匹配,那么程序就会有未定义的行为。

构造它们的初始化器可以在构造函数的成员初始化器列表中指定,在函数体之前的冒号之后:

void Tree::Tree(const std::istream& input)
  : height_(/* initializer for height_ */),
    leaf_(/* initializer for leaf_ */)
{
    //...
}

(代替圆括号,也可以使用大括号进行列表初始化。)

leaf_ 的初始化器中,可以使用 height_ 的值。

由于您可能需要做一些工作才能从输入中获取 height_,因此您可能想为此编写一个额外的函数并为 /* initializer for height_ */.

调用它