-
结构体的基本概念
结构体是一种用户自定义的数据类型,用于存储不同类型的数据。 -
结构体的定义和使用
可以通过以下方式定义结构体:
struct 结构体名 {
数据类型 成员1;
数据类型 成员2;
// ...
};
使用结构体时,可以创建结构体变量,有三种方式:
struct 结构体名 变量名
struct 结构体名 变量名 = {成员1值, 成员2值, ...}
- 在定义结构体时顺便创建变量
例如,创建一个表示学生的结构体:
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int age;
int score;
};
int main() {
Student s1; // 创建结构体变量
s1.name = "张三";
s1.age = 18;
s1.score = 100;
cout << "姓名:" << s1.name << " 年龄:" << s1.age << " 分数:" << s1.score << endl;
Student s2 = {"李四", 19, 80}; // 创建结构体变量并初始化
cout << "姓名:" << s2.name << " 年龄:" << s2.age << " 分数:" << s2.score << endl;
Student s3 = {"王五", 20, 100}; // 在定义结构体时顺便创建变量
cout << "姓名:" << s3.name << " 年龄:" << s3.age << " 分数:" << s3.score << endl;
return 0;
}
- 结构体数组
结构体数组用于将多个结构体对象放入数组中,便于维护和操作。
使用语法如下:
struct 结构体名 数组名[元素个数] = {{成员1值, 成员2值, ...}, {成员1值, 成员2值, ...}, ...};
例如,创建一个学生结构体数组:
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int age;
int score;
};
int main() {
Student stuArray[3] = {
{"张三", 18, 100},
{"李四", 28, 99},
{"王五", 38, 66}
};
stuArray[2].name = "赵六";
stuArray[2].age = 80;
stuArray[2].score = 60;
for (int i = 0; i < 3; i++) {
cout << "姓名: " << stuArray[i].name
<< " 年龄:" << stuArray[i].age
<< " 分数:" << stuArray[i].score << endl;
}
return 0;
}
- 结构体指针
结构体指针可以通过指针访问结构体中的成员。
使用操作符 ->
可以通过结构体指针访问结构体的成员。
例如,使用结构体指针访问学生结构体的成员:
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int age;
int score;
};
int main() {
Student s = {"张三", 18, 100}; // 创建结构体变量
Student* p = &s; // 指针指向结构体变量
cout << "姓名:" << p->name
<< " 年龄:" << p->age
<< " 分数:" << p->score << endl;
return 0;
}