“int [0]”C++ 的初始值设定项太多

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21152171/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:30:19  来源:igfitidea点击:

too many initializers for 'int [0]' c++

c++arraysc++11structinitialization

提问by cppython

First:

第一的:

int k[] ={1,2,3,4,5};

Second:

第二:

struct slk
{
    int k[] ={1,2,3,4,5};
};

for those two statements, why does the first one pass the compilation but the second one give me

对于这两个语句,为什么第一个通过编译但第二个给了我

error:too many initializers for 'int [0]'. the compilation would passed if I set k[5];

错误:“int [0]”的初始值设定项过多。如果我设置 k[5],编译就会通过;

What does this error message means? Note: code tested on GNU GCC version 4.7.2

这个错误信息是什么意思?注意:代码在 GNU GCC 版本 4.7.2 上测试

回答by jtomschroeder

In C++11, in-class member initializers are allowed, but basically act the same as initializing in a member initialization list. Therefore, the size of the array must be explicitly stated.

在 C++11 中,允许类内成员初始化,但基本上与在成员初始化列表中初始化相同。因此,必须明确说明数组的大小。

Stroustrup has a short explanation on his website here.

斯特劳斯在他的网站的简短说明这里

The error message means that you are providing too many items for an array of length 0, which is what int []evaluates to in that context.

该错误消息意味着您为长度为 0 的数组提供了太多项目,这就是int []在该上下文中的计算结果。

回答by Chris Zhang

In the first example, something (actual memory allocation) is actually happening. The computer easily counts the number of items given to it and uses this as the capacity. In the second use, as part of a struct, the array is simply part of the template of a struct. In the second case, a size must explicitly be given and known at compile-time. There is no automatic counting here. It's in a similar vein to function declarations versus definitions as well as variable declarations (tells type but memory is untouched) and their invocation/use (where the program acts).

在第一个示例中,实际发生了一些事情(实际内存分配)。计算机很容易计算给它的物品数量,并将其用作容量。在第二次使用中,作为结构的一部分,数组只是结构模板的一部分。在第二种情况下,必须在编译时明确给出和知道大小。这里没有自动计数。它与函数声明与定义以及变量声明(告诉类型但内存未受影响)及其调用/使用(程序在何处执行)类似。

回答by Dannie

Probably cause in a structthe compiler needs you to specify the size explicitly.

可能导致struct编译器需要您明确指定大小。

C initialize array within structure(pun intended)

C 在结构中初始化数组(双关语)

回答by user3200739

These are two completely different contexts:

这是两个完全不同的上下文:

The first is a variable declaration (with an initialiser clause).

第一个是变量声明(带有初始化子句)。

The second is a type definition.

第二个是类型定义。