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++:数组的构造函数初始值设定项
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
