[C++基础入门](七):结构体

目录

基本概念

定义和使用

结构体数组

结构体指针

结构体嵌套

结构体做参数


基本概念

  • 属于用户自定义的数据类型,允许用户存储不同的数据类型

定义和使用

语法: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++基础入门](六):指针

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值