C++ 内联数组初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4583628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inline array initialization
提问by Gzorg
I was used to using
我习惯使用
new int[] {1,2,3,4,5};
for initializing array. But it seems nowadays, this does not work anymore, i have to explicitly state how many elements there are, with
用于初始化数组。但现在看来,这不再有效,我必须明确说明有多少元素,
new int[5] {1,2,3,4,5};
so compilers forgot how to count ?
所以编译器忘记了如何计数?
And to make this a closed question, is there a way to omit the number of elements ?
为了使这是一个封闭的问题,有没有办法省略元素的数量?
回答by CB Bailey
This has never worked in the current version of C++, you have only been able to zero-initialize(or not initialize) dynamically allocated arrays.
这在当前版本的 C++ 中从未奏效,您只能对动态分配的数组进行零初始化(或不初始化)。
What has always worked is non-dynamically allocated array initialization:
一直有效的是非动态分配的数组初始化:
int myarray[] = {1, 2, 3, 4, 5};
Perhaps you are confusing it with this?
也许你把它与这个混淆了?
Even in C++0x it is not legal syntax to omit the explicit array size specifier in a new expression.
即使在 C++0x 中,在 new 表达式中省略显式数组大小说明符也是不合法的语法。
回答by Oleg Danu
C++ have never allowed to initialize array with an unknown size of elements like above. The only 2 ways I know, is specify the number of elements or use pointers.
C++ 从未允许使用上述未知大小的元素初始化数组。我知道的唯一两种方法是指定元素的数量或使用指针。