C++四种类型转换是什么

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

  1. static_cast - 静态类型转换
    最常用的转换,用于良性转换
cpp 复制代码
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 - 动态类型转换
    用于多态类型的向下转换,运行时检查类型安全
cpp 复制代码
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 属性
cpp 复制代码
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 - 重新解释转换
    低级别的重新解释,最危险的转换
cpp 复制代码
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);
相关推荐
卷无止境2 天前
C++ 的Eigen 库全解析
c++
卷无止境2 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴2 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18004 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴4 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨5 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4569 天前
C++进阶(1)——前景提要
c++
夜悊9 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴9 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt00110 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp