const修饰指针 结构体中const使用场景 常量引用

const修饰指针有三种情况

  1. const修饰指针 --- 常量指针
  2. const修饰常量 --- 指针常量
  3. const即修饰指针,又修饰常量

示例

 1 int main() {
 2 
 3     int a = 10;
 4     int b = 10;
 5 
 6     //const修饰的是指针,指针指向可以改,指针指向的值不可以更改
 7     const int * p1 = &a; 
 8     p1 = &b; //正确
 9     //*p1 = 100;  报错
10     
11 
12     //const修饰的是常量,指针指向不可以改,指针指向的值可以更改
13     int * const p2 = &a;
14     //p2 = &b; //错误
15     *p2 = 100; //正确
16 
17     //const既修饰指针又修饰常量
18     const int * const p3 = &a;
19     //p3 = &b; //错误
20     //*p3 = 100; //错误
21 
22     system("pause");
23 
24     return 0;
25 }

技巧:看const右侧紧跟着的是指针还是常量, 是指针就是常量指针,是常量就是指针常量

 


结构体中 const使用场景

作用:用const来防止误操作

示例:

 1 //学生结构体定义
 2 struct student
 3 {
 4     //成员列表
 5     string name;  //姓名
 6     int age;      //年龄
 7     int score;    //分数
 8 };
 9 
10 //const使用场景
11 void printStudent(const student *stu) //加const防止函数体中的误操作
12 {
13     //stu->age = 100; //操作失败,因为加了const修饰
14     cout << "姓名:" << stu->name << " 年龄:" << stu->age << " 分数:" << stu->score << endl;
15 
16 }
17 
18 int main() {
19 
20     student stu = { "张三",18,100 };
21 
22     printStudent(&stu);
23 
24     system("pause");
25 
26     return 0;
27 }

 

常量引用

作用:常量引用主要用来修饰形参,防止误操作

在函数形参列表中,可以加==const修饰形参==,防止形参改变实参

 示例:

 1 //引用使用的场景,通常用来修饰形参
 2 void showValue(const int& v) {
 3     //v += 10;
 4     cout << v << endl;
 5 }
 6 
 7 int main() {
 8 
 9     //int& ref = 10;  引用本身需要一个合法的内存空间,因此这行错误
10     //加入const就可以了,编译器优化代码,int temp = 10; const int& ref = temp;
11     const int& ref = 10;
12 
13     //ref = 100;  //加入const后不可以修改变量
14     cout << ref << endl;
15 
16     //函数中利用常量引用防止误操作修改实参
17     int a = 10;
18     showValue(a);
19 
20     system("pause");
21 
22     return 0;
23 }

 

posted @ 2022-04-09 19:30  xiaoxie001  阅读(145)  评论(0编辑  收藏  举报