C++ 补充 & C++ 11 - C++ reinterpret

    技术2022-07-14  76

    reinterpret_cast用法详解

    重新解释类型(挂羊头,卖狗肉) 不同类型间的互转,数值与指针间的互转

    用法: TYPE b = reinterpret_cast ( a ) TYPE必须是一个指针、引用、算术类型、函数指针.

    忠告:滥用 reinterpret_cast 运算符可能很容易带来风险。 除非所需转换本身是低级别的,否则应使用其他强制转换运算符之一。

    demo 代码(一)

    #include <iostream> using namespace std; class Animal { public: void cry() { cout << "动物叫" << endl; } }; class Cat :public Animal { public: void cry() { cout << "喵喵" << endl; } }; class Dog :public Animal { void cry() { cout << "旺旺" << endl; } }; int main(void) { /* 用法一 数值与指针之间的转换 */ int* p = reinterpret_cast<int*>(0x999999); int val = reinterpret_cast<int>(p); /* 用法二 不同类型指针和引用之间的转换 */ Dog dog1; Animal* a1 = &dog1; a1->cry(); Dog* dog1_p = reinterpret_cast<Dog*>(a1); Dog* dog2_p = static_cast<Dog*>(a1); /* 如果能用 static_cast, static_cast 优先 */ //Cat* cat1_p = static_cast<Cat*>(a1); //Cat* cat2_p = static_cast<Cat*>(dog1_p); /* NO! 不同类型指针转换不能使用static_cast */ Cat* cat2_p = reinterpret_cast<Cat*>(dog1_p); Animal a2 = dog1; Dog& dog3 = reinterpret_cast<Dog&>(a2); /* 引用强转用法 */ dog1_p->cry(); dog2_p->cry(); cat2_p->cry(); system("pause"); return 0; }

    编译:

    结语:

    时间: 2020-07-02

    Processed: 0.015, SQL: 10