首页 > 其他 > 详细

const关键字在结构体中的使用场景

时间:2021-07-26 09:13:10      阅读:21      评论:0      收藏:0      [点我收藏+]

const用来防止误操作:

具体实例看以下代码实例:

?

?

#include<iostream>
using namespace std;
//结构体中const使用场景
//使用const来防止误操作
struct Student {
	string name;
	int age;
	int score;
};
//可以将函数中的形参类型改为指针(4个字节),可以减少内存占用
void printStruct01(struct Student s)
{
	cout <<"名字"<< s.name <<"年龄"<< s.age <<"分数"<< s.score << endl;
}

//可以将函数中的形参类型改为指针(4个字节),可以减少内存占用
void printStruct02(const struct Student *s)
{
	 //由于加了const,不能再改变数据,一旦修改就会报错,防止误操作
	//s->name = "jsoja";
	cout << "名字" << s->name << "年龄" << s->age << "分数" << s->score << endl;
}


int main()
{
	//创建结构体变量
	struct Student s1 = { "zhsnagsan",15,20 };

	//值传递 (相当于值拷贝)
	printStruct01(s1);
	printStruct02(&s1);

	//通过函数打印结构体信息



	return 0;
}

?

const关键字在结构体中的使用场景

原文:https://blog.51cto.com/u_15286849/3183621

(0)
(0)
   
举报
评论 一句话评论(0
分享档案
最新文章
教程昨日排行
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!