带有复杂参数的初始化列表C
Initialization list c++ with complex parameter
我有一个类:
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>()) {}
相关文章:
- C++类 - 初始化列表 - 递归 - 按值传递
- 在初始化列表之外手动调用基类的构造函数
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- std::map与谓词与初始化列表
- 类内初始化与构造函数初始化列表的顺序
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- C++初始化列表与分配值
- C++初始化列表中的向量集大小或调整大小
- 在构造函数初始化列表中使用 std::variant
- emplace_back初始化列表错误,当初始化列表在独立变量上工作时
- 解释了构造函数成员初始化列表
- 使用初始化列表时如何获取私有数据?
- 用初始化列表和超类构造函数声明子类构造函数的正确方式
- 如何在成员初始化列表中声明共享指针
- 庞大的初始化列表,如何修复"fatal error C1060: compiler is out of heap space"
- 我可以检查初始化列表中设置的构造函数主体中的变量吗
- 使用整数初始化列表初始化长双精度的向量
- 是否可以在C++中使用初始化列表设置数组的特定成员?