目录
基本概念
- 属于用户自定义的数据类型,允许用户存储不同的数据类型
定义和使用
语法:struct 结构体名 { 结构体成员列表 };
定义:
- struct 结构体名 变量名;
- struct 结构体名 变量名 = {成员1值, 成员2值, .... };
- 声明结构体时顺便定义变量(不建议使用);
使用操作符‘.’访问成员变量
#include <iostream>
using namespace std;
//声明
struct student {
string name;
int age;
int score;
};
//定义 可以省略struct
student s1;
struct student s2 = {"zhangsan", 23, 90};
//声明时顺便定义变量(不常用)
struct sss {
string name;
int age;
int score;
}Stu;
int main(void)
{
Stu.name = "张三"; //使用 . 访问成员
Stu.age = 24;
Stu.score = 56;
s1.name = "李四";
system("pause");
return 0;
}
结构体数组
- 即:是一个数组,数组的每个元素都是一个结构体
#include <iostream>
using namespace std;
//声明
struct student {
string name;
int age;
int score;
};
int main(void)
{
struct student arr[3] = { {"zs", 18, 90}, };
arr[1].name = "Meichao";
cout << "arr[0]'s name:" << arr[0].name << endl;
cout << "arr[1]'s name:" << arr[1].name << endl;
system("pause");
return 0;
}
结构体指针
- 即:是一个指针,指针指向的地址的数据类型是一个结构体
- 结构体指针使用操作符‘->’访问成员变量
结构体嵌套
#include <iostream>
using namespace std;
struct student {
string name;
int age;
int score;
};
struct teacher {
int id;
string name;
int age;
struct student stu;
};
struct student s1 = {"zhangsan", 12, 89};
struct teacher t1 = { 1, "laoshi", 34, s1};
int main(void)
{
struct teacher* tr = &t1;
cout << "t1's name: " << tr->name << endl;
cout << "t1's stu's name:" << (tr->stu).name << endl;
system("pause");
return 0;
}
结构体做参数
- 值传递
- 地址传递(可以修改实际参数的值)
推荐使用地址传递,减少内存使用空间,可根据情况使用const修饰防止误操作
#include <iostream>
using namespace std;
struct student {
string name;
int age;
int score;
};
struct student s1 = {"zhangsan", 12, 89};
struct student* ptr = &s1;
void GetStuName(const struct student stu)
{
cout << "原学生姓名:" << stu.name << endl;
}
void ChangeName(struct student* stu, const string NewName)
{
stu->name = NewName;
}
int main(void)
{
GetStuName(s1);
ChangeName(ptr, "Lisi");
cout << "新学生姓名:" << s1.name << endl;
system("pause");
return 0;
}
基础部分已学完!!!!
视频:戳这里_B站大学
推荐文章:[C++基础入门](六):指针