[英]C++ struct “Incomplete type is not allowed”
Does anyone know what this error means and why it is occurring when I am trying to define an array inside a struct? 有谁知道此错误的含义以及当我尝试在结构内定义数组时为什么会发生此错误?
struct test{
int idk[] = { 1,2,3 };
};
Why is the array idk incomplete type or something? 为什么数组idk的类型不完整?
Thanks in advance. 提前致谢。
Ps. PS。 I need this so I can access these arrays from the test struct.
我需要这样做,以便可以从测试结构访问这些数组。
When declaring a variable in a local scope (like in a function body, for example), you can do this and the compiler will not complain, it will deduce that you mean an array of int of 3 elements. 在局部范围内声明变量时(例如,在函数体中),您可以执行此操作,并且编译器不会抱怨,这将意味着您表示一个包含3个元素的int数组。
void someFunc()
{
int idk[] = { 1,2,3 }; // Ok, so idk is in fact a int[3];
// Do whatever work...
}
When doing the same thing in a class or struct declaration, the compiler do not want to deduce that for you, so basically, you need to be stricter. 当在类或结构声明中执行相同的操作时,编译器不想为您推断出这一点,因此,基本上,您需要更加严格。
For a complete reason of why, you can see here ( What is the reason for not being able to deduce array size from initializer-string in member variable? ) among other places. 关于其原因的完整原因,您可以在此处看到其他地方( 无法从成员变量中的initializer-string推断数组大小的原因是什么? )。
So, to make it work, you need to so this: 因此,要使其正常工作,您需要这样做:
struct test
{
int idk[3] = { 1,2,3 };
};
As to why people might dislike this question, well this is kind of a mundane question and really any search in google will yield the answer. 至于为什么人们可能不喜欢这个问题,那么这是一个平凡的问题,实际上,在Google中进行任何搜索都会得到答案。 The compiler itself will back out the error, and just searching for that will most of the time find the answer for you.
编译器本身将排除该错误,并且在大多数情况下,只需进行搜索即可找到答案。
Basically, this kind of question is telling the community here you did not do any research prior to asking your question. 基本上,这种问题是在告诉社区您在提出问题之前没有进行任何研究。
With visual studio compiler, it creates this error: Error C2997 'test::idk': array bound cannot be deduced from an in-class initializer 使用Visual Studio编译器时,它会产生以下错误:错误C2997'test :: idk':无法从类内初始化程序推导出数组绑定
Which is pretty explicit. 这是非常明确的。
Mick 米克
array bound cannot be deduced from an in-class initializer
So changing the snippet to 因此将代码段更改为
struct test{
int idk[3] = { 1,2,3 };
results in successful compilation. 结果编译成功。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.