作用:用const来防止误操作
//8.7 const使用场景
#include<iostream>
#include<string>
using namespace std;
struct student
{
string name;
int age;
int score;
};
void printStudent(const student *s)//将函数中的形参改为指针,可以减少内存空间,而且不会复制新的副本
{
//s->age = 150; //只读不可写;加入const之后,一旦有修改的操作就会报错,可以防止我们的误操作
cout << "姓名: " << s->name << "学生年龄: " << s->age << "分数: " << s->score << endl;
}
int main()
{
//创建结构体变量
struct student s = { "张三", 20 , 85 };
printStudent(&s);
//printStudent1(&s);
// cout << "姓名: " << t.name << "老师编号: " << t.id << "年龄: " << t.age << endl;
cout << "姓名: " << s.name << "学生年龄: " << s.age << "分数: " << s.score << endl;
system("pause");
return 0;
}
本文通过一个具体的C++示例,介绍了如何利用const关键字来保护数据不被误修改,展示了const在函数参数中的使用场景,并解释了其对于提高程序稳定性和可维护性的价值。
972

被折叠的 条评论
为什么被折叠?



