reinterpret_cast 用法

本文详细介绍了C++中reinterpret_cast的使用方法及其注意事项。通过示例代码展示了如何将不同类型的指针相互转换,并讨论了在不同平台上的表现差异。同时,文章还探讨了reinterpret_cast与C语言强制类型转换的区别。

reinterpret_cast  用法
语法:
reinterpret_cast<type-name>(expression)
如果 type-name 和 expression 的位数一样,那么就能进行这种转换。reinterpret_cast 的安全性完全由程序员控制。
C语言的强制类型转换有时会忽略这一限制:转换源与转换目标的位数是否相同。例如,long 可以强制转换为 int,即“长数”强制转换为“短数”。char 可以强制转换为 short,即“短数”转换为“长数”。但是,在64位X86平台上,指针值不能强制转换为 int ,只能强制转换为 long 。
请看示例代码:

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
40
41
42
#include<cstdio>
int main(){
  printf("sizeof shortintlonglong longfloatdoublevoid * : \
    %lu, %lu, %lu, %lu, %lu, %lu, %lu\n", \
    sizeof(short), sizeof(int),sizeof(long),sizeof(long long),sizeof(float),sizeof(double),sizeof(void *));
  long ldata = 0x1234567890abcdef;
  long *pl = &ldata;
  printf("pl=%p\n", pl);
  void *pvoid = pl;
  printf("pvoid=%p\n", pvoid);
  struct stFormat{
    int start;
    int end;
  };
  stFormat *pst = reinterpret_cast<stFormat *>(pl);
  printf("pst: %p, %#x, %#x\n", pst, pst->start, pst->end);
  void (*pf)(void) = reinterpret_cast<void (*)(void)>(pl);
  printf("pf=%p\n", pf);
#if 0
  //error: invalid cast from type ‘long int’ to type ‘int’
  int idata1 = reinterpret_cast<int>(ldata); 
  printf("idata1 = %#x\n", idata1);
#endif
   
  int idata2 = int(ldata); 
  printf("idata2 = %#x\n", idata2);
  char ch = 'a';
  short sht1 = short(ch);
  printf("sht1 = %#x\n", sht1);
#if 0
  //error: cast from ‘long int*’ to ‘short int’ loses precision [-fpermissive]
  short sht2 = short(pl);
  printf("sht2 = %#x\n", sht2);
#endif
  long lval = long(pl);
  printf("lval = %lx\n", lval);
#if 0
  //error: cast from ‘long int*’ to ‘int’ loses precision [-fpermissive]
  int ival = int(pl);
  printf("ival = %d\n", ival);
#endif
}

测试结果:
sizeof short, int, long, long long, float, double, void * :     2, 4, 8, 8, 4, 8, 8
pl=0x7fff9ad82500
pvoid=0x7fff9ad82500
pst: 0x7fff9ad82500, 0x90abcdef, 0x12345678
pf=0x7fff9ad82500
idata2 = 0x90abcdef
sht1 = 0x61
lval = 7fff9ad82500






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






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值