C++:数组的构造函数初始值设定项

2021-12-30 00:00:00 constructor initializer 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.

相关文章