C/C++沉思-----const的简单用法

本文详细解析了C++中const关键字的多种应用场景,包括与指针、函数结合使用的方法及注意事项,帮助读者深入理解const如何提升代码质量和安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 const与指针

1  指针常量 

int*const ptr

指针常量,即不可以将ptr修改为指向内存中另一处的地址,但可以用它来改变它所指向的地址处的数据内容。

  1. //const.cpp  
  2. #include <iostream>  
  3. #include <cstring>  
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     int temp = 4;  
  9.     cout << temp << endl;  
  10.   
  11.     //ptr被const修饰 定义时必须初始化  
  12.     int *const ptr = &temp;  
  13.     *ptr = 5;  
  14.     cout << temp << endl;  
  15.   
  16.     return 0;  
  17. }  

程序运行截图:

 

2 常量指针

const int *ptr;    (常量指针的另一种写法int const *ptr)

常量指针,即可以将ptr修改为指向内存中另一处的地址,但不可以用它来改变它所指向的地址处的数据内容。

  1. //const.cpp  
  2. #include <iostream>  
  3. #include <cstring>  
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.   
  9.     int temp1 = 4;  
  10.     int temp2 = 5;  
  11.   
  12.     const int *ptr;  
  13.     ptr = &temp1;  
  14.     cout << "*ptr:" << *ptr << endl;  
  15.   
  16.     ptr = &temp2;  
  17.     cout << "*ptr:" << *ptr << endl;  
  18.   
  19.     return 0;  
  20. }  


 

程序运行截图:

 

指向const常量的const指针

const int *const ptr;   (另一种写法int const *const ptr

指向const常量的const指针,即ptr所指向的内存地址和所指向的地址处的数据内容都不能被修改

 

PSconst离谁比较近,则谁的值不能被改变

 

 

二  const与函数

1 const修饰函数的参数

const使该参数在函数中不能被改变

void copy(char *strDes, const char *strsrc)

strsrc指针所指向的值在copy函数中不能被改变,如果意外的改动该指针,编译器会报错

 

注意:

不用将“值传递”的方式(void copy(int x, in y))加const修饰,因为函数会自动产生临时变量用于复制该参数,参数本来就不需要保护。

 

2 const修饰函数的返回值

const int* add(int x, int y);

add函数的返回值(即指针)的内容不能被修改,该返回值只能被赋值给加const修饰的同类型指针

const int *p = add(3, 5);

 

注意:

如果函数返回值是“值传递方式”(int add(int x, int y),由于函数会把返回值复制到外部临时的存储单元中,加const修饰没有意义。

 

3 const成员函数

任何不会修改类的数据成员(即函数中的变量)的函数都应该声明为const类型。在编写const成员函数时,如果不小心修改了数据成员,或者调用了其他非const成员函数,编译器会报错,这种做法将大大提高程序的健壮性。

  1. //test.cpp  
  2. class test  
  3. {  
  4. public:  
  5.     void set(int);  
  6.     //const成员函数  
  7.     int get()const;          
  8. private:  
  9.     int value;  
  10. };  
  11.   
  12. int test::get()const  
  13. {  
  14.     //编译错误 修改数据成员value  
  15.     ++value;  
  16.     //编译错误 调用了非const函数  
  17.     set(5);  
  18.     return value;  
  19. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值