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);
}
posted @ 2022-09-14 21:08  岁月飞扬  阅读(71)  评论(0编辑  收藏  举报