C++ struct “Incomplete type is not allowed”

孤者浪人 提交于 2020-02-15 08:02:58

问题


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?

Thanks in advance.

Ps. I need this so I can access these arrays from the test struct.


回答1:


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.

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.

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. 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

Which is pretty explicit.

Mick




回答2:


 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.



来源:https://stackoverflow.com/questions/35106733/c-struct-incomplete-type-is-not-allowed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!