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
short
,
int
,
long
,
long
long
,
float
,
double
,
void
* : \
%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,如需转载请自行联系原作者