C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++四种类型转换

C++四种类型转换全解

作者:折戟不必沉沙

C++的四种命名式类型转换操作符是:static_cast、dynamic_cast、const_cast 和 reinterpret_cast,‌‌本文介绍C++四种类型转换是什么,感兴趣的朋友一起看看吧

C++ 中的四种类型转换是 C++ 引入的更安全、更明确的类型转换操作符,相比 C 风格的强制转换更加精细和可控:

  1. static_cast​ - 静态类型转换
    最常用的转换,用于良性转换
int i = 10;
double d = static_cast<double>(i);  // 基本类型转换
class Base {};
class Derived : public Base {};
Base* b = new Derived();
Derived* d = static_cast<Derived*>(b);  // 向下转换(不安全,不检查)
int* p = nullptr;
void* vp = static_cast<void*>(p);  // void* 转换
  1. dynamic_cast​ - 动态类型转换
    用于多态类型的向下转换,运行时检查类型安全
class Base { virtual void foo() {} };
class Derived : public Base {};
Base* b = new Derived();
// 安全的向下转换
Derived* d = dynamic_cast<Derived*>(b);
if (d != nullptr) {  // 转换成功
    // 使用 d
}
// 转换失败返回 nullptr(对指针)或抛出异常(对引用)
  1. const_cast​ - 常量性转换
    添加或移除 const、volatile 属性
const int ci = 10;
int* pi = const_cast<int*>(&ci);  // 移除 const
*pi = 20;  // 未定义行为,ci 原本是 const
void print(char* str) { /* 修改 str */ }
const char* s = "hello";
print(const_cast<char*>(s));  // 临时移除 const
  1. reinterpret_cast​ - 重新解释转换
    低级别的重新解释,最危险的转换
int* p = new int(65);
char* c = reinterpret_cast<char*>(p);  // 重新解释指针类型
int i = 0x12345678;
float f = reinterpret_cast<float&>(i);  // 二进制重新解释
// 函数指针转换
typedef void (*FuncPtr)();
FuncPtr func = reinterpret_cast<FuncPtr>(0x12345678);

到此这篇关于C++四种类型转换全解的文章就介绍到这了,更多相关C++四种类型转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文