人生如逆旅, 我亦是行人。|
2022-09-14 21:08阅读: 78评论: 0推荐: 0

C++ 新特性 强制转换 reinterpret_cast

reinterpret_cast

  • 用于进行各种不同类型的转换
    • 不同类型指针之间
    • 不同类型因引用之间
    • 指针和能容纳指针的整数类型直接的转换
  • 编译期处理,执行的是逐字节复制的操作
  • 类似于显示强转,后果自负
#include <iostream>

using namespace std;

class CFather {

};

class CSon : public CFather {

};

int main() {

    // 显示强转
    int n = 1;
    int *p = (int*)n;


    // 用于转换各种高危险的转换方式
    // 整型转指针
    int *q = reinterpret_cast<int*>(n);

    // 各种类型的指针转换
    char *pCh = reinterpret_cast<char*>(p);

    // 父类、子类指针的转换
    CSon* pSon;
    CFather* pFather = nullptr;
    pSon = reinterpret_cast<CSon*>(pFather); // 不存在检查

    int& w = n;
    char& f = reinterpret_cast<char&>(w);
}

本文作者:岁月飞扬

本文链接:https://www.cnblogs.com/jerry-1015/p/16560551.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   岁月飞扬  阅读(78)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起