这个结构是定义的,那么为什么函数认为它不是呢?

This struct is defined, so why does the function think it isn't?

本文关键字:函数 为什么 结构 定义      更新时间:2023-10-16

C++新手。只是制作一个简单的结构/数组程序。为什么我不能像在这里一样传递一个结构数组?

int NumGrads();
int main()
{
      struct Student {
          int id;
          bool isGrad;
      }; 
    const size_t size = 2;
    Student s1, s2;
    Student students[size] = { { 123, true },
                             { 124, false } };
    NumGrads(students, size);
    std::cin.get();
    return 0;
}
int NumGrads(Student Stu[], size_t size){
}

我理解这一定与传递引用或值有关,但如果我在main()中定义了它,那么NumGrads参数肯定不会出错?

您的结构在main的内部被定义为,而NumGrads函数在main外部被定义为。

这意味着你的结构是在你的函数可以看到它的范围之外定义的

将结构的定义移动到main之上,问题就解决了。

Studentmain()中定义。在main之外定义它,使其与NumGrads:在同一范围内

 struct Student
 {
      int id;
      bool isGrad;
 };
 int main()
 {
      ...
 } 

结构定义是main的本地定义。main之外的任何东西都看不到它,包括您的NumGrads定义。在函数中包含结构定义并不是一件很常见的事情——通常情况下,您会在命名空间范围内使用它。

此外,您的NumGrads声明与定义的参数类型不一致。

// Define Student at namespace scope
struct Student {
    int id;
    bool isGrad;
}; 
int NumGrads(Student[], size_t); // The argument types are now correct
int main()
{
    // ...
}
int NumGrads(Student Stu[], size_t size){
}

struct Student是在main内部声明的,因此int NumGrads看不到它。此外,在main中调用该函数时,该函数是未声明的。此时,唯一可用的声明是int NumGrads(),这是一个不同的函数。