作者:
2016年5月15日 (最後更新:2016年5月16日)

C++ 型別轉換

評分:4.0/5 (472 票)
*****
型別轉換(Casting)是一個轉換過程,透過該過程,資料可以從一種型別更改為另一種型別。C++ 有兩種型別的轉換:

隱式轉換:由編譯器自動執行的轉換,無需程式設計師干預。

例如
1
2
int iVariable = 10;
    float fVariable = iVariable; //Assigning an int to a float will trigger a conversion.  


顯式轉換:僅在程式設計師明確指定時才執行的轉換。

例如
1
2
int iVariable = 20;
    float fVariable = (float) iVariable / 10;



在 C++ 中,有四種類型的轉換運算子。
1
2
3
4
- static_cast
- const_cast
- reinterpret_cast
- dynamic_cast

在本文中,我們將只探討前三種轉換運算子,因為 dynamic_cast 非常不同,幾乎只用於處理多型性,這不在本文的討論範圍之內。

static_cast
格式
static_cast<型別>(表示式);
例如
float fVariable = static_cast<float>(iVariable); /* 該語句將 int 型別的 iVariable 轉換為 float 型別。*/

看一眼上面的程式碼,你會立刻明白這次型別轉換的目的,因為它非常明確。static_cast 告訴編譯器嘗試在兩種不同的資料型別之間進行轉換。它可以在內建型別之間轉換,即使會損失精度。此外,static_cast 運算子還可以在相關的指標型別之間進行轉換。

例如
1
2
3
4
int* pToInt = &iVariable;
    float* pToFloat = &fVariable;
    
    float* pResult = static_cast<float*>(pToInt); //Will not work as the pointers are not related (they are of different types).  



const_cast
格式
const_cast<型別>(表示式);
例如
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void aFunction(int* a)
{
    cout << *a << endl;
}

int main()
{
    int a = 10;
    const int* iVariable = &a;
    
    aFunction(const_cast<int*>(iVariable)); 
/*Since the function designer did not specify the parameter as const int*, we can strip the const-ness of the pointer iVariable to pass it into the function. 
Make sure that the function will not modify the value. */

    return 0;
} 



const_cast 可能是最少使用的轉換運算子之一,它不在不同型別之間進行轉換,而是改變表示式的“常量性”(const-ness)。它可以將非 const 的內容變為 const,也可以透過去除 const 使其變為 volatile/可變的。一般來說,你不會想在程式中使用這種特定的轉換。如果你發現自己正在使用這個轉換,你應該停下來重新思考你的設計。

reinterpret_cast
格式
reinterpret_cast<型別>(表示式);

reinterpret_cast 可以說是最強大的轉換運算子之一,它可以將任何內建型別轉換為任何其他型別,也可以將任何指標型別轉換為另一種指標型別。但是,它不能去除變數的常量性或易變性(volatile-ness)。然而,它可以不顧型別安全或常量性,在內建資料型別和指標之間進行轉換。這種特定的轉換運算子只應在絕對必要時使用。


希望本文對任何正在努力理解型別轉換理論的人有所幫助。

程式設計愉快。