C++ const_cast用法

const_cast是一种C++运算符,主要是用来去除复合类型中const和volatile属性(没有真正去除)。

变量本身的const属性是不能去除的,要想修改变量的值,一般是去除指针(或引用)的const属性,再进行间接修改。

用法:const_cast<type>(expression)

通过const_cast运算符,也只能将const type*转换为type*,将const type&转换为type&。

也就是说源类型和目标类型除了const属性不同,其他地方完全相同。

复制代码
 1 #include<iostream>
 2 using namespace std;
 3 void ConstTest1(){
 4     const int a = 5;
 5     int *p;
 6     p = const_cast<int*>(&a);
 7     (*p)++;
 8     cout<<a<<endl;
 9     cout<<*p<<endl;
10     
11 }
12 void ConstTest2(){
13     int i;
14     cout<<"please input a integer:";
15     cin>>i;
16     const int a = i;
17     int &r = const_cast<int &>(a);
18     r++;
19     cout<<a<<endl;
20 }
21 int main(){
22     ConstTest1();
23     ConstTest2();
24     return 0;
25 }
26 输出:
27 5
28 6
29 若输入7
30 则输出8
复制代码

解释为什么输出8:

当常变量为 const int j =i 时,直接输出j时,编译器不能进行优化,也就是不能够直接用i代替j;

当常变量为const int j =5时,直接输出j时,编译器会进行优化,也就是用文字常量5直接代替j;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值