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

C++: constructor initializer for arrays(C++:数组的构造函数初始值设定项)

本文介绍了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++:数组的构造函数初始值设定项

基础教程推荐