6.1 基本概念

  • 用户自定义
  • 语法:struct 结构体名{ 结构体成员列表};
  • 创建结构体变量的方式
    • struct 结构体名 变量名;
    • struct 结构体名 变量名 = {成员1, 成员2};
    • 定义结构体时创建 ```cpp struct Student { string name; int age; int score; }s3;

struct Student s1; s1.name = “Tom”; s1.age = 11; s1.score = 100; struct Student s2={“Jerry”,12,100}; Student s4; //关键字struct可以省略

  1. <a name="varZS"></a>
  2. ## 6.2 结构体数组
  3. - 如果要删除某项,该项后的所有数据向前移动一个
  4. ```cpp
  5. struct Student stuArray[2] =
  6. {
  7. {"Jerry",12,100},
  8. {"Tom",12,100}
  9. }
  10. stuArray[1].name

6.3 结构体指针

  • 通过指针访问结构体成员
  • 操作符 ->
    struct Student S={"Jerry",12,100};
    struct Student *p = &s;
    p->name
    

    6.4 结构体嵌套结构体

    ```cpp struct Student { string name; int age; int score; };

struct Teacher { int id string name; struct Student stu; };

Teacher t; t.stu.name

<a name="U9hUr"></a>
## 
<a name="bXMHt"></a>
## 6.5 结构体做函数参数

- 值传递
```cpp
void printStudent(struct Student s)
{
    s.name
}

Student s;
//值传递
printStudent(s)
  • 地址传递(节约内存) ```cpp void printStudent(struct Student *s) {
    s->name }

Student s; //值传递 printStudent(&s)

<a name="PC9z6"></a>
## 
<a name="YCeR5"></a>
## 6.6 结构体const

- 防止误操作  
```cpp
void printStudent(const Student *s)
{    
    s->name//只能读,不能写
}

Student s;
//值传递
printStudent(&s)

6.7 实践

  • include

  • srand((unsigned int)time(NULL));
  • int random = rand()%60 + 40; ```cpp // // main.cpp // c++_learning // // Created by BiancaGuo on 2021/5/8. //

include

include

include

using namespace std;

struct student{ string name; float score; }; struct teacher{ string name; student stu[5]; };

void allocateSpace(struct teacher tArray[],int size) { for(int i=0;i<size;++i) { tArray[i].name = “Teach_” + to_string(i); int stusize = sizeof(tArray[i].stu)/sizeof(tArray[i].stu[0]);

    for(int j=0;j<stusize;++j)
    {
        tArray[i].stu[j].name = "Student_"+to_string(j);
        int random = rand()%60 + 40; //0~99 随机分数
        tArray[i].stu[j].score = random;
    }
}

}

void printTArray(const teacher tArray[],int size) { for(int i=0;i<size;++i) { cout<< tArray[i].name <<”:”<<endl; int stusize = sizeof(tArray[i].stu)/sizeof(tArray[i].stu[0]); for(int j=0;j<stusize;++j) { cout<<tArray[i].stu[j].name << endl; cout<<tArray[i].stu[j].score << endl; } } cout<<endl; } int main() { srand((unsigned int)time(NULL)); //增加随机数种子 teacher teachers[3]; int len = sizeof(teachers)/sizeof(teachers[0]); allocateSpace(teachers,len); printTArray(teachers,len); }

```