C++类型转换----reinterpret_cast

reinterpret_cast的功能比static_cast的功能更为强大,但安全性也更为的差,可以用它完成C++语法上不允许的\
转换,在某些情况下程序员有需要的转换。例如,可以把某种引用或指针类型转换为其他引用类型或指针类型(两\
个类型可以不相关),这个关键字还经常将指针转换为void*,以及将void*转换为指针。

下面通过代码说明reinterpret_cast的使用:

#include <iostream>

using namespace std;

//测试int 和 void*的相互转化
void test_voidpointer(void *data){
    int d = reinterpret_cast<int>(data);

    cout << d << endl;
}

//定义连个无关类A, B
class A{

};

class B{

};

int _tmain(int argc, _TCHAR* argv[])
{
    //void* 和in的相互转化,这里应该注意一下64位平台和32位平台指针的大小不同
    test_voidpointer(reinterpret_cast<void *>(20));

    //A a;
    B b;

    //a = reinterpret_cast<A>(b); //编译通不过,b不知指针或者引用

    //下面是指针或引用的转化
    A *pa = reinterpret_cast<A*>(&b);
    A &ra = reinterpret_cast<A&>(b);

    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值