C/C++结构体嵌套声明问题

版本:VS2019
#include<string>
#include<iostream>
using namespace std;

struct Teacher 
{
    string tname;
    struct Student Sarr[5];
};

struct Student
{
    string sname;
    int score;
};

报错:“Teacher::Sarr”使用未定义的 struct“Student”
提问:如何将Teacher结构体写在Student结构体的上面,并且不报错?结构体有没有类似函数体的那种写在最前面的声明语句。

在 C++ 中,对于结构体的成员函数,可以采用先声明后定义的方式,以实现结构体成员函数写在结构体定义的上面。
但是在结构体内部的成员变量,不支持先声明后定义的方式。因此,如果要在 Teacher 结构体中使用 Student 结构体,需要在 Teacher 结构体定义的前面添加一个结构体声明,例如:

struct Student; // 先声明 Student 结构体
 
struct Teacher 
{
    string tname;
    struct Student Sarr[5];
};
 
struct Student
{
    string sname;
    int score;
};

这样,在定义 Teacher 结构体时,就可以使用 Student 结构体了。同时,注意要把 Student 结构体定义在 Teacher 结构体的前面,否则还是会报错。
另外,结构体内部的成员变量的定义顺序,对于结构体大小和内存布局都有影响,所以一般按照自然顺序来定义。

先申明,后使用,这是原则
所以要在Teacher结构前,先声明学生结构才行

#include<string>
#include<iostream>
using namespace std;

struct Student
{
    string sname;
    int score;
};
struct Teacher 
{
    string tname;
    struct Student Sarr[5];
};