C/C++备忘录(三):结构体基础

一、定义与使用

//定义
struct student{
	string name;
	int score;
};
//初始化
//方法一
student s1;
s1.name = "xxx";
s1.score = 90;
//方法二
student s2 = {"xxx", 90};
//方法三 
struct student{
	string name;
	int score;
}s3;
s3.name = "xxx";
s3.score = 90;

二、结构体数组

struct student{
	string name;
	int score;
};
//创建结构体数组
student stuArray[3] = 
{
	{"A", 90},
	{"B", 85},
	{"C", 80} 
};
//给结构体数组中的元素赋值
stuArray[2].name = "D";
stuArray[2].score = 95;
//遍历结构体数组
for(int i = 0; i < 3; i++){
	cout << "姓名: " << stuArray[i].name << "分数: " << stuArray[i].score << endl;
}

三、结构体指针

student s = { "A" , 18};
//创建p指针指向结构体变量s
student *p = &s;
//通过指针访问结构体变量中的数据
cout << "姓名: " << p->name << "分数: " << p->score << endl;

四、结构体嵌套

struct student{
	string name;
	int score;
};
struct teacher{
	int id;
	string name;
	student stu;	//嵌套
};
teacher t;
t.id = 10000;
t.name = "haha";
t.stu.name = "lala";
t.stu.score = 90;	//嵌套赋值
cout << t.name << t.id << t.stu.name << t.stu.score;

五、结构体做函数参数

//1.值传递
void printStu1(student s){
	cout << s.name << s.score;
}
//2.地址传递
void printStu2(student *p){
	cout << p->name << p->score;
}
student s;
printStu2(&s);

六、结构体中const的使用场景

//值传递原理是将原来的结构体成员都复制一份,再传到函数中,数据量大的情况很占用内存空间。
//地址传递不会复制数据,指针本身只占用4字节,能很大节省内存空,但有可能会修改到原有结构体数据。
void printStu(const student *s)	//加入const防止函数体中的误操作,保护结构体。
{
	// s->score = 100; 加入const之后,一旦有修改操作,会报错。
	cout << s->name << s->score;
}
student s;
printStu(&s);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值