struct结构体

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

一、结构体使用方式

1.1 结构体创建变量的三种方式

方式一

  • 结构体中使用基本数据类型进行变量声明,默认变量的访问权限都是public的

先声明后赋值

struct Student
{
	//结构体中不能使用类,只能使用基本数据类型
	char name[16];
	int age;
	int score;
};

struct Student stu1;
	stu1.name = "张一";
	stu1.age = 13;
	stu1.score = 100;

方式二:

直接使用花括号赋值

	//方式二
	struct Student stu2 = { "李四",19,60 };

方式三:

在结构体上声明变量

struct Student
{
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
	//在结构体中嵌套一个类
	Teacher t;
}stu3; //结构体变量创建方式3 


	//方式三
	stu3 = { "李四",19,60 };

1.2 结构体数组

	//结构体数组的声明方式
	struct Student arr[3] = {
		{"张三",18,99},
		{"李四",17,59},
		{"王五",16,57},
	};

可以使用正常的for循环来对数组进行遍历

1.3 结构体指针

class Teacher {
public:
	int age;
	string name;
};
struct Student
{
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
	//在结构体中嵌套一个类
	Teacher t;
}; //结构体变量创建方式3 


	struct Student stu1;
	stu1.name = "张一";
	stu1.age = 13;
	stu1.score = 100;
	stu1.t.age = 10;
	stu1.t.name = "张老师";


struct Student* p = &stu1;
	p->age = 14;

	cout << "结构体中通过修改之后的学生年龄为" << stu1.age <<  endl;

![image.png](https://img-blog.csdnimg.cn/img_convert/f43014017d176d25389854b22ad84761.png#clientId=ub08d1bae-888c-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=252&id=u06fc0736&margin=[object Object]&name=image.png&originHeight=303&originWidth=1132&originalType=binary&ratio=1&rotation=0&showTitle=false&size=65626&status=done&style=none&taskId=u774a9224-9fa6-40f8-886c-a581e87ab1d&title=&width=943.333295848636)
通过指针修改之后的打印情况

1.4 结构体嵌套结构体

结构体嵌套结构体

struct Student
{
	//成员列表
	string name;  //姓名
	int age;      //年龄
	int score;    //分数
	//在结构体中嵌套一个类
	Teacher t;
}stu3; //结构体变量创建方式3 


struct teacher {
	int id;
	string name;
	int age;
	struct Student stu;
};

1.5 结构体做函数参数

方法一:

值传递

void dostruct(struct Student stu) {
	stu.age = 10;
	cout << "方法调用结构体修改之后的学生年龄为" << stu.age << endl;
}

main函数中调用

dostruct(stu2);

方法二:

址传递

void dostruct(struct Student *stu) {
	stu-> age = 11;
	cout << "方法调用结构体修改之后的学生年龄为" << stu->age << endl;
}

函数中传递的是一个指针
main函数中调用,传递的实参是地址

	dostruct(&stu2);

1.6 结构体中const使用场景

在函数的形参上面加上const修饰符修饰,可以防止函数中对结构体数据进行修改

//加上const防止对结构体中的数据进行误操作
void dostruct( const struct Student* stu) {
	//stu->age = 11; 加了const修饰之后不能修改结构体中的数据
	cout << "方法调用结构体修改之后的学生年龄为" << stu->age << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值