static_cast、dynamic_cast、reinterpret_cast、const_cast以及C強制類型轉換的區別


static_cast

1. 基礎類型之間互轉如:float轉成int、int轉成unsigned int等

2. 指針與void*之間互轉。如:float*轉成void*、CBase*轉成void*、函數指針轉成void*、void*轉成CBase*等

3. 派生類指針【引用】轉成基類指針【引用】。如:Derive*轉成Base*、Derive&轉成Base&等

4. 非virtual繼承時,可將基類指針【引用】轉成派生類指針【引用】多繼承時,會做偏移處理)。如:Base*轉成Derive*、Base&轉成Derive&等

dynamic_cast  專門用於處理多態機制,對繼承體系內的對象(類中必須含有至少一個虛函數)的指針【引用】進行轉換,轉換時會進行類型檢查;vc在編譯時要帶上/EHsc /GR

如果能轉換會返回對應的指針【引用】;不能轉換時,指針會返回空,引用則拋出std::bad_cast異常(const std::bad_cast& e)

注:由於std::bad_cast類型定義在typeinfo頭文件中,固需要#include<typeinfo>

另外,對於菱形非virtual繼承、非public繼承,轉換引用時也會拋出std::bad_cast異常

reinterpret_cast  對指針【引用】進行原始轉換,不做任何偏移處理(當然:多繼承時,也不會做偏移處理

1. 將指針【引用】轉換成整型。如:float*轉成int、CBase*轉成int、float&轉成int、CBase&轉成int等

float f1 = 1.0f; CBase o1;
int n1 = reinterpret_cast<int>(&f1);
int n2 = reinterpret_cast<int>(&o1);
int n3 = reinterpret_cast<int&>(f1);
int n4 = reinterpret_cast<int&>(o1);

2. 指針【引用】之間互轉。如:float*轉成int*、CBase&轉成int&、CBase*轉成CBase2*、CBase&轉成CBase2&等

float f1 = 1.0f;  CBase1 o1;
int* n1 = reinterpret_cast<int*>(&f1);
int& n2 = reinterpret_cast<int&>(o1);
CBase2* o21 = reinterpret_cast<CBase2*>(&o1);
CBase2& o22 = reinterpret_cast<CBase2&>(o1);

const_cast   去掉或增加constvolatile特性

C類型強制轉換   形式:(type)objecttype(object)

最好是使用type(object);原因是:在某些編譯器下,(type)object不會調用構造函數,而type(object)下則肯定會調用構造函數

C類型強制轉換會按照以下順序進行嘗試轉換:

a. const_cast
b. static_cast
c. static_cast, then const_cast
d. reinterpret_cast
f. reinterpret_cast, then const_cast


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM