带有复杂参数的初始化列表C

Initialization list c++ with complex parameter

本文关键字:初始化 列表 参数 复杂      更新时间:2023-10-16

我有一个类:

class Foo {
private:
  Other bar;
};

和其他类:

class Other {
public:
Other(std::list<int> l, ...other parameters...);
};

Other没有默认文件,我无法添加。如何初始化属性栏?我的意思是我需要创建一个列表,需要添加一些项目等等,因此使用初始化列表确实很难,因为我需要编写代码来填写列表。我能怎么做?我想我可以使用指针,但是我想避免动态分配。

您可以编写一个函数来创建对象,并在启动器列表中使用它:

static Other make_bar() {
    std::list<int> l;
    // fill the list, do whatever else you need
    return Other(l, ...);
}
Foo() : bar(make_bar()) {}

,或者您可以使用boost::optional之类的东西推迟初始化而无需动态分配。

您可以在Foo中实现构造函数:

Foo() : bar(std::list<int>()) {}