C++: constructor initializer for arrays(C++:数组的构造函数初始值设定项)
问题描述
我脑抽筋了...如何在 C++ 中正确初始化对象数组?
I'm having a brain cramp... how do I initialize an array of objects properly in C++?
非数组示例:
struct Foo { Foo(int x) { /* ... */ } };
struct Bar {
Foo foo;
Bar() : foo(4) {}
};
数组示例:
struct Foo { Foo(int x) { /* ... */ } };
struct Baz {
Foo foo[3];
// ??? I know the following syntax is wrong, but what's correct?
Baz() : foo[0](4), foo[1](5), foo[2](6) {}
};
Wild &疯狂的解决方法的想法很受欢迎,但在我的情况下,它们对我没有帮助.我正在开发一个嵌入式处理器,其中 std::vector 和其他 STL 构造不可用,显而易见的解决方法是创建一个默认构造函数并具有一个可以调用的显式 init() 方法在构建时间之后,这样我就不必使用初始化程序了.(这是我被 Java 的 final 关键字 + 构造函数的灵活性所宠坏的情况之一.)
edit: Wild & crazy workaround ideas are appreciated, but they won't help me in my case. I'm working on an embedded processor where std::vector and other STL constructs are not available, and the obvious workaround is to make a default constructor and have an explicit init() method that can be called after construction-time, so that I don't have to use initializers at all. (This is one of those cases where I've gotten spoiled by Java's final keyword + flexibility with constructors.)
推荐答案
没办法.你需要一个数组成员的默认构造函数,它会被调用,之后,你可以在构造函数中进行任何你想要的初始化.
There is no way. You need a default constructor for array members and it will be called, afterwards, you can do any initialization you want in the constructor.
这篇关于C++:数组的构造函数初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++:数组的构造函数初始值设定项
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
