C++ 结构体中const使用场景

1、值传递:值传递中值的改变不会影响主函数中的值。

#include<iostream>
using namespace std;
struct student
{
	string name;
	int age;
	int score;
};

void printStudents(student s)
{
	//值传递:他的值的改变不会改变主函数的值
	s.age = 20;
	cout << "学生的姓名:" << s.name << " 年龄:" << s.age << " 得分:" << s.score << endl;
}

int main()
{
	student s = { "张三",23,80 };
	printStudents(s);

	cout << "主函数中的学生姓名:" << s.name << " 年龄:" << s.age << " 得分:" << s.score << endl;
	system("pause");
	return 0;
}

可以看到上述printStudents中s.age = 20;但是他并没有改变主函数中的age值;结果如下所示

2、地址传递:值改变会影响到主函数中的值

为了防止误操作,我们使用const

#include<iostream>
using namespace std;

//const防止误操作
struct student
{
	string name;
	int age;
	int score;
};

void printStudents(const student *s)
{
	//地址传递,使用了const防止误操作,所以会提示错误
	//p->age = 20;
	cout << "学生的姓名:" << s->name << " 年龄:" << s->age << " 得分:" << s->score << endl;
}

int main()
{
	student s = { "张三",23,80 };
	printStudents(&s);

	cout << "主函数中的学生姓名:" << s.name << " 年龄:" << s.age << " 得分:" << s.score << endl;
	system("pause");
	return 0;
}

 使用了const防止误操作,而且使用指针操作的话,可以节省内存空间!

结果如下:

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值