C++ 中有四種 Cast:const_cast
、static_cast
、dynamic_cast
、reinterpret_cast
,這些 cast function 不是 marco 也不屬於 STL Libray,是 C++ 的保留字(Keyword)。
const_cast 的用途是移除 const 的屬性。
強烈建議不要用,除非有必須。
用法:const_cast<T>(ptr)
,其中 ptr 必為指標或 refrence
範例如下:
執行於 compile-time,功能與 C-Style cast 相似,但更安全。
範例:
執行於 run-time,用於 polymorphism,up cast (Derived -> Base) 或 down cast (Base -> Derived)。
若已知型別轉換不會出錯,建議使用 static_cast,執行時間較快。
範例:
是個很危險的存在,有不可兼容的危險(importable)。
用途是強制轉換型別,不論資料大小是否相同。
範例: