为什么需要结构体

要存一个学生的信息,用 int 存学号、用 string 存姓名、用 double 存成绩,三个散落的变量管起来很乱。结构体(struct)把这些不同类型的数据打包成一个整体,一个变量就代表"一个学生"。

定义与使用

struct 定义一种新类型,里面的每个数据项叫成员,访问成员用点号:

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

struct Student {
    int id;           // 学号
    string name;      // 姓名
    double score;     // 成绩
};

int main() {
    Student s1 = {1001, "小雪", 92.5};
    cout << s1.name << " 的成绩是 " << s1.score << endl;
    // 输出:小雪 的成绩是 92.5
    return 0;
}

注意结构体定义末尾的分号不能少,漏掉是新手最常见的编译错误之一。

整体赋值

结构体变量可以直接赋给另一个变量,成员会被逐个复制,之后互不影响:

Student s1 = {1001, "小雪", 92.5};
Student s2 = s1;          // s2 的三个成员与 s1 相同
s2.name = "阿梨";
cout << s1.name << " " << s2.name << endl;
// 输出:小雪 阿梨(改 s2 不影响 s1)

结构体与函数

结构体可以作为参数传给函数。只读就按值传,想修改原变量就要用引用传递:

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

struct Student {
    int id;
    string name;
    double score;
};

// 加分:用引用才能改到原变量
void addBonus(Student& s, double bonus) {
    s.score += bonus;
}

int main() {
    Student s1 = {1001, "小雪", 92.5};
    addBonus(s1, 5);
    cout << s1.name << " 现在的成绩是 " << s1.score << endl;
    // 输出:小雪 现在的成绩是 97.5
    return 0;
}

嵌套结构体

成员也可以是另一个结构体,用来表达层次关系:

struct Date {
    int year;
    int month;
    int day;
};

struct Book {
    string title;
    Date publish;     // 出版日期
};

Book b = {"C++ 入门", {2026, 10, 1}};
cout << b.publish.year << " 年出版" << endl;
// 输出:2026 年出版

结构体数组

把多个结构体放进数组,就能批量管理一组数据:

Student class3[3] = {
    {1001, "小雪", 92.5},
    {1002, "阿梨", 88.0},
    {1003, "大壮", 79.5}
};

double total = 0;
for (int i = 0; i < 3; i++) {
    total += class3[i].score;
}
cout << "平均分:" << total / 3 << endl;
// 输出:平均分:86.6667

小结

结构体是 C++ 里组织数据的第一步:struct 定义类型、点号访问成员、引用传递让函数能修改原数据、嵌套与结构体数组支撑更复杂的数据表达。以后学到类(class)时会发现语法一脉相承,只是多了成员函数和访问控制这些面向对象的能力。