【问题标题】:Why does my code say that it has an incomplete type even after I tried declaring it?为什么我的代码即使在我尝试声明它之后仍说它的类型不完整?
【发布时间】:2021-12-26 05:34:07
【问题描述】:

我正在编写一个程序,它以表格的形式显示一些学生的考试成绩,然后计算并显示平均值。运行代码后,我收到以下错误(也如下图所示): 变量的类型不完整 “组织学生” 结构学生 st[50]; ^ 注意:“学生”的前向声明 struct students st[50];

我已经声明了学生并尝试声明 st,但我不确定问题是什么。以下是我的代码的打字版本和屏幕截图:

#include <iostream>
using namespace std;
int Main()
{
  int students;

   struct students st[50]; 
   return 0;
}

Code errors Picture of typed code

【问题讨论】:

  • 您将students 声明为int,您没有定义一个名为studentsstruct,因此struct students 没有引用已定义的类型,因此出现错误。跨度>
  • 旁注:using namespace std; 是一种反模式。请不要那样做。

标签: c++ struct compiler-errors declaration incomplete-type


【解决方案1】:

此声明中使用的结构学生

struct students st[50];

尚未定义。所以编译器会报错,因为你不能声明一个元素类型不完整的数组。

您应该先定义结构,然后再在数组声明中使用其详细名称,例如

include <string>

struct students
{
    std::string name;
};

int main()
{
    int students;

    struct students st[50];

    //...
}

【讨论】:

  • 注意:在 C++ 中,一旦定义了 students 结构,就不再需要在调用代码中使用 struct 关键字。所以虽然struct students st[50]; 会编译,但写students st[50]; 就足够了。如果你真的想这样做,这里使用详细名称允许int 类型的变量studentsstudents 类共存。
【解决方案2】:

你必须先定义它。你也可以使用这种风格。

struct student{
    ...
};

int main{
    student* st[50];
    for(int i=0; i<50;i++)
        st[i]=new student;
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2023-02-20
    • 2021-12-24
    • 1970-01-01
    • 2015-06-21
    • 2021-09-01
    • 2017-06-30
    相关资源
    最近更新 更多