qfedu-cpp-level/day7/homework/h2_3.cpp

26 lines
801 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 请简述static_cast、dynamic_cast和reinterpret_cast的区别并给出示例代码进行说明。
// reinterpret_cast :
// 重新解释转换,用于不同类型之间的强制转换,即将一个指针或引用转换为完全不相关的类型。它可以将任何指针类型转换为其他指针类型,也可以将整数类型转换为指针类型,反之亦然。它非常危险,不进行类型检查。
#include <iostream>
using namespace std;
int num = 10;
int *np = &num;
double *dp = reinterpret_cast<double *>(np); // 将整数类型指针转换为浮点数类型指针
class Base
{
public:
virtual void foo() {}
};
int main()
{
Base *base = new Base();
int *intp = reinterpret_cast<int *>(base); // 将基类指针转换为整数类型指针
return 0;
}