c和c++的強制類型轉換


我們知道c語言中的類型轉換只有一種,

TYPE b = (TYPE)a;

而在c++中按照不同作用的轉換類型將其細分為三個顯示類型轉換符號static_cast, const_cast, reinterpret_cast,這種顯示轉換可以提供更豐富的含義和功能,更好的類型檢查機制,方便代碼的維護。

1.static_cast

  • 主要用於相關類型之間的轉換,如c的基本數據類型char,int,double等之間,以及基類和子類之間轉換(沒有dynamic_cast安全),可能會有字節轉換,不可以轉換不相關類型如int*和double*,以及沒有繼承關系的類指針
  • void*與其他類型指針之間的轉換
double bv = 100.0
int i = (int)bv;  //c style, 0x64
int iv2 = static_cast<int>(bv); //0x64
int iv2 = reinterpret_cast<int>(bv); //error,

double bv = 100.0;
double *pbv = &bv;
int *iv1 = (int*)pbv; //c style, right
int *iv2 = static_cast<int*>(pbv); //error: invalid static_cast from type `double*' to type `int*'
int *iv2 = reinterpret_cast<int*>(pbv); //right, 
void *piv1 = (void*)pbv;
void *piv2 = static_cast<void*>(pbv);
int *piv3 = static_cast<int*>(piv2); //right

2.reinterpret_cast

  • 轉換的類型type必須是一個指針或引用,僅僅按照轉換后的類型重新解釋字節,並不會做字節轉換
  • 如果將非指針變量轉換成指針,變量大小必須與指針大小相等。
  • 移植性差
int lv = 100;
long long llv =100;
int *piv1 = (int*)lv;  //c style, do’not check size
int *piv2 = reinterpret_cast<int*>(lv); //lv is treated as pointer
piv2 = reinterpret_cast<int*>(llv); // warning, different size

3.const_cast

去除指針或者引用的const或volatile屬性

//c style
const char const_char = 'a';
char *pch = &const_char;  //error: invalid conversion from `const char*' to `char*'
char *pch = (char*)&const_char; //right
*pch = 'c'; 

//c++style
const char const_char = 'a';
char chv = const_cast<char>(const_char); //error, invalid use of const_cast with type `char', which is not a pointer, reference, nor a pointer-to-data-member type
const char *pch = &const_char;
char *chv = const_cast<char*>(&const_char);//right
*chv=’c’;

總結:這三種與c對應的強制類型轉換符號都是編譯時確定的,RTTI的dynamic_cast和c沒有關系,以后再專門介紹。


免責聲明!

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



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