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);
相关推荐
ch0sen1pm6 分钟前
刚学完 CAS 原子操作,我花了一晚上写了三个无锁队列
c++
qeen876 分钟前
【C++】vector的模拟实现详解(二)
c++·学习·算法·迭代器·stl
2301_794461576 分钟前
Activiti/BPMN 2.0 的 4 种网关
java·服务器·开发语言
147API13 分钟前
Claude Tag 进入 Slack 后,团队智能体需要哪些任务与审计字段
java·开发语言·数据库
熬夜苦读学习22 分钟前
QT_信号和槽
开发语言·qt
代码雕刻家25 分钟前
编程语法细节
java·c语言·开发语言
j7~26 分钟前
【C++】C++ 继承全解析:从基本语法到菱形继承的底层原理
开发语言·c++·继承·组合·虚继承·#暑假·七月创作之星博客挑战赛
数行拙笔30 分钟前
C++客户端---String类型
开发语言·c++·bootstrap
影寂ldy36 分钟前
C# Task 进阶:WaitAll / WaitAny / WhenAll / WhenAny
开发语言·c#
左左右右左右摇晃1 小时前
手写Tomcat原理整理
java·开发语言·笔记·tomcat