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);
相关推荐
technology_x5 小时前
液冷超充站设备厂家哪家好?2026年功率与散热对比
java·开发语言
SurpriseDPD5 小时前
bpftrace‑tasks 工具代码分析
开发语言·python
千谦阙听6 小时前
C++篇:类和对象(上)
开发语言·c++
许彰午6 小时前
07-SqlBuilder六法
java·开发语言·低代码·架构
BS30813_vx6 小时前
【编号:01652】Spring Boot村务管理系统:财务公开、党建活动与计生服务一体化实战
开发语言·python
Jul1en_6 小时前
【Java 脚手架】封装通用工具类-3
java·开发语言·redis·缓存·ai·bootstrap·rabbitmq
学习星球6 小时前
2026年AI Agent全栈开发实战——从Prompt到Production
开发语言·人工智能·prompt
_Narcissus_6 小时前
分治&递归
数据结构·c++·笔记·算法·leetcode·递归·分治
Fluxart.ai6 小时前
商品多角度图怎么做?Flux Art 从白底图到规格图、包装图的 10 步教程
开发语言·前端·javascript