且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++结构“不允许使用不完整的类型"

更新时间:2022-06-23 05:07:19

在局部范围内声明变量时(例如,在函数体中),您可以执行此操作,并且编译器不会抱怨,它会推断出表示由3个元素组成的int数组.

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 };
};

关于为什么人们可能不喜欢这个问题,这真是一个平凡的问题,实际上,在Google中进行任何搜索都会得到答案.编译器本身将排除该错​​误,并且在大多数情况下,只需进行搜索即可找到答案.

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.

使用Visual Studio编译器时,会产生以下错误: 错误C2997'test :: idk':无法从类内初始化程序推导数组绑定

With visual studio compiler, it creates this error: Error C2997 'test::idk': array bound cannot be deduced from an in-class initializer

这是很明确的.

密克