首页 > 代码库 > reinterpret_cast 用法
reinterpret_cast 用法
reinterpret_cast 用法
语法:
reinterpret_cast<type-name>(expression)
如果 type-name 和 expression 的位数一样,那么就能进行这种转换。reinterpret_cast 的安全性完全由程序员控制。
C语言的强制类型转换有时会忽略这一限制:转换源与转换目标的位数是否相同。例如,long 可以强制转换为 int,即“长数”强制转换为“短数”。char 可以强制转换为 short,即“短数”转换为“长数”。但是,在64位X86平台上,指针值不能强制转换为 int ,只能强制转换为 long 。
请看示例代码:
#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
本文出自 “用C++写诗” 博客,谢绝转载!
reinterpret_cast 用法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。