C++ 引入四種命名轉換運算符,替代 C 風格的 (Type)expr,使意圖明確、便於搜索、安全性更強。
static_cast<Type>(expr)
int→double, double→int)、void* 與具體指針互轉、隱式轉換的顯式調用。const/volatile,不能在不相關類型間轉換。int i = 0x7fff; long l = static_cast<long>(i); // 非強制擴展 int j = static_cast<int>(3.14); // 窄化,截斷小數 void* vp = &i; float* fp = static_cast<float*>(vp); // void* → 具體指針
const_cast<Type>(expr)
const 或 volatile 資格,底層類型必須相同。const 的舊式 API,或實現「邏輯常量性」(如 mutable 緩存)。const 的對象導致未定義行為。const int ci = 10; int* p = const_cast<int*>(&ci); // 去除 const volatile int vi = 0; int* q = const_cast<int*>(&vi); // 去除 volatile
reinterpret_cast<Type>(expr)
struct* → char* 逐字節訪問)。struct X { int a[100]; };
X x;
int* ip = reinterpret_cast<int*>(&x); // 視為 int 數組
for (int* p = ip; p < ip+100; ++p) *p = 0; // 清零
print(reinterpret_cast<X*>(ip)); // 轉回
dynamic_cast<Type>(expr)
nullptr;引用轉換失敗拋 bad_cast。class Base { virtual ~Base() {} };
class Derived : public Base {};
Base* pb = new Derived;
Derived* pd = dynamic_cast<Derived*>(pb); // 成功
Base* pb2 = new Base;
Derived* pd2 = dynamic_cast<Derived*>(pb2); // 失敗,返回 nullptr
| 運算符 | 主要用途 | 運行時檢查 | 去除 const | 不相關類型 |
|---|---|---|---|---|
| static_cast | 良性/窄化/上行/void* | 無 | 否 | 否 |
| const_cast | const/volatile 修改 | 無 | 是 | 否 |
| reinterpret_cast | 位模式重新解釋 | 無 | 否 | 是 |
| dynamic_cast | 多態下行/交叉轉換 | 有 (RTTI) | 否 | 否 |
static_cast,覆蓋 90%+ 場景。const 只用 const_cast,且極少使用。reinterpret_cast 只在極底層代碼(序列化、硬件接口)使用,並加詳細註釋。dynamic_cast,考慮用虛函數/訪問者模式替代。