const_cast 用法

本文详细介绍了C++中const_cast操作符的使用方法及其注意事项。包括如何将const对象的地址赋给非const指针,以及如何将非const对象的地址赋给const指针。并通过示例代码展示了不同情况下const_cast的操作效果。

const_cast 用法
语法:
const_cast<type-name>(expression);
作用:
1. 将const对象的地址赋给同类型的非const指针。例如:
   const int val = 100;
   int * pv = const_cast<int *>(&val);

   但是,仍然无法通过这个非const指针pv来修改const对象val。所以,我觉得 const_cast 没有什么用。

2. 将非const对象的地址赋给同类型的const指针。例如:
   int val = 100;
   const int * pc = const_cast<const int *>(&val);
3. type-name 和 expression 的类型必须相同。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<cstdio>
int main()
{
  // assign address of "int object" to "int *" pointer.
  {
    int val_1 = 12;
    int *ptr_1 = const_cast<int *>(&val_1);
    *ptr_1 += 100;
    printf("val_1 = %d\n", val_1);
  }
  // assign address of "const int object" to "int *" pointer.
  {
    const int val_2 = 34;
    int *ptr_2 = const_cast<int *>(&val_2);
    *ptr_2 += 100;
    printf("val_2 = %d\n", val_2);
  }
  // assign address of "int object" to "const int *" pointer.
  {
    int val_3 = 56;
    const int *ptr_3 = const_cast<const int *>(&val_3);
    //*ptr_3 += 100; //error: assignment of read-only location ‘* ptr_3’
    printf("val_3 = %d\n", val_3);
  }
  // assign address of "const int object" to "const int *" pointer.
  {
    const int val_4 = 78;
    const int *ptr_4 = const_cast<const int *>(&val_4);
    //*ptr_4 += 100; error: assignment of read-only location ‘* ptr_4’
    printf("val_4 = %d\n", val_4);
  }
  // assign address of "const int object" to "char *" pointer.
  {
    const int val_5 = 78;
    //char *ptr_5 = const_cast<char *>(&val_5); error: invalid const_cast from type ‘const int*’ to type ‘char*’
    //*ptr_5 += 100; error: assignment of read-only location ‘* ptr_5’
    printf("val_5 = %d\n", val_5);
  }
}

测试结果:
frank@userver:~/project/CppPrimerPlus/Chapter 15$ ./a.out 
val_1 = 112
val_2 = 34
val_3 = 56
val_4 = 78
val_5 = 78




      本文转自FrankNie0101 51CTO博客,原文链接:http://blog.51cto.com/frankniefaquan/1939622,如需转载请自行联系原作者






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值