简体   繁体   中英

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?

Thanks in advance.

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.

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

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM