C ++:数组的构造函数初始值 [英] C++: constructor initializer for arrays
问题描述
我有一个脑筋痉挛...如何在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) {}
};
编辑:疯狂的解决方法的想法是赞赏,但他们不会帮助我在我的情况。我正在一个嵌入式处理器,其中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 ++:数组的构造函数初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!