结构体种const的使用场景(7)


作用:用const来防止误操作

使用场景:

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 //定义学生结构体
 6 struct Student
 7 {
 8     string name;
 9     int age;
10     int score;
11 };
12 
13 //使用地址传递和引用的方式,可以减少内存空间,而且不会复制出新的副本来
14 void print_stu_info(const struct Student *p)
15 {
16     //p->age = 150;//用于地址传递和引用有形参改变,实参也改变的缺陷,为了弥补这个缺陷,所以使用const来修饰,来防止误操作
17     cout << "姓名:" << p->name << "  年龄:" << p->age << " 分数:" << p->score << endl;
18 }
19 
20 
21 int main(void)
22 {
23     //创建结构体变量
24     struct Student s = {"张三",18,100};
25 
26     //通过函数来打印学生信息
27     print_stu_info(&s);
28 
29     system("pause");
30     return 0;
31 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM