C++中4种不同的类型转换
在 C++ 中,有四种主要的类型转换操作符:static_cast
、dynamic_cast
、const_cast
和reinterpret_cast
。每种转换操作符都适用于不同的场景:
1. static_cast
适用场景:用于各种基本类型转换,基本类型包括int
, uint8_t
, enum
等,但以下3种情况除外:
- 指针:只能通过
dynamic_cast
或者是reinterpret_cast
- const转非const:只能通过
const_cast
- volatile转非volatile: 只能通过
const_cast
示例:
- 将浮点数转换为整数。
float f = 3.5; int i = static_cast<int>(f); // i 的值为 3
- 将整数转换为枚举类型。
enum Color { RED, GREEN, BLUE }; int n = 1; Color color = static_cast<Color>(n); // color 是 GREEN
2. dynamic_cast
适用场景:主要用于基类指针/引用和派生类指针/引用的相互转换。如果转换的双方不存在继承关系,会返回nullptr
。
示例:
- 在类的继承关系中转换类型。
class Base { virtual void dummy() {} }; class Derived : public Base { int a; }; Base *b = new Derived; Derived *d = dynamic_cast<Derived*>(b);
3. const_cast
适用场景:用于修改类型的const
或volatile
属性,可以给某个对象加上/移除const
或者volatile
属性。不过一般用于移除对象的const
属性。
不知道volatile
关键字的作用?移步这里大话C++之:volatile关键字,5分钟讲明白😁
示例:
- 从一个常量对象移除
const
限定。const int x = 10; int* modifiable = const_cast<int*>(&x); *modifiable = 20; // 不推荐这样做,可能会导致未定义行为
4. reinterpret_cast
适用场景:前3种转换方法无法满足时,使用reinterpret_cast
。reinterpret_cast
等价于C语言里的强制类型转换,可以随意转换。
示例:
- 将指针类型转换为足够大的整数类型。
char *p = new char[10]; std::size_t addr = reinterpret_cast<std::size_t>(p);
总结
static_cast
是最常用的类型转换,适用于基本类型之间的转换。dynamic_cast
主要用于基类指针或引用与派生类指针或引用之间的转换 。const_cast
用于修改或移除对象的const或volatile属性。reinterpret_cast
等效于C语言里强制类型转换。