导航菜单

C++编程/结构体和类
课程进度 51% · 第10/18章10/18章 · 标签 1/4
1

结构体定义与使用

结构体是 C++ 中的一种用户自定义数据类型,用于将不同类型的数据组合在一起。

cpp
1
// 结构体定义
2
struct Student {
3
string name;
4
int age;
5
double gpa;
6
};
7
 
8
// 创建结构体变量
9
Student student1;
10
student1.name = "张三";
11
student1.age = 20;
12
student1.gpa = 3.8;
13
 
14
// 创建并初始化
15
Student student2 = {"李四", 22, 3.9};
16
 
17
// 结构体数组
18
Student class_roster[30];
19
 
20
// 结构体指针
21
Student* ptr = &student1;
22
cout << ptr->name; // 箭头操作符
23
cout << (*ptr).age; // 等价于 ptr->age

📖结构体成员默认是公开的(public),可以包含函数(方法)

2

结构体中的函数

cpp
1
struct Rectangle {
2
double width;
3
double height;
4
 
5
// 结构体中的函数
6
double area() {
7
return width * height;
8
}
9
double perimeter() {
10
return 2 * (width + height);
11
}
12
};
13
 
14
// 结构体作为函数参数
15
void printStudent(Student s) {
16
cout << "姓名: " << s.name << endl;
17
cout << "年龄: " << s.age << endl;
18
}
19
 
20
// 使用引用避免复制
21
void updateGPA(Student& s, double newGPA) {
22
s.gpa = newGPA;
23
}
24
 
25
// 结构体嵌套
26
struct Point { double x, y; };
27
struct Line {
28
Point start, end;
29
double length() {
30
return sqrt(pow(end.x-start.x,2) +
31
pow(end.y-start.y,2));
32
}
33
};