跳轉到內容

D(程式語言)/d2/型別轉換

50% developed
來自華夏公益教科書,自由的教科書

第 5 課:型別轉換

[編輯 | 編輯原始碼]

在本課中,您將學習如何隱式和顯式地轉換變數的型別。

入門程式碼

[編輯 | 編輯原始碼]
import std.stdio;
 
void main()
{
    short a = 10;
    int b = a;
 
    // short c = b;
    // Error:  cannot implicitly convert 
    // expression b of type int to short
 
    short c = cast(short)b;
 
    char d = 'd';
    byte e = 100;
    wchar dw = 'd';
 
    int f = d + e + dw;
    writeln(f); //300
 
    float g1 = 3.3;
    float g2 = 3.3;
    float g3 = 3.4;
    int h = cast(int)(g1 + g2 + g3);
    writeln(h); //10
    int i = cast(int)g1 + cast(int)g2 + cast(int)g3;
    writeln(i); //9
}

隱式整型轉換

[編輯 | 編輯原始碼]

只要目標型別比原始型別更寬,就可以將整型型別的物件轉換為另一整型型別的物件。這些轉換是隱式的。

boolint
byteint
ubyteint
shortint
ushortint
charint
wcharint
dcharuint

顯式轉換

[編輯 | 編輯原始碼]

強制轉換是告訴編譯器嘗試強制物件更改型別的一種方法。在 D 中,您可以透過編寫 cast(type) 來實現。

  • 您不能使用強制轉換將整數值轉換為字串(反之亦然)。以後會學到一個庫函式來實現這個功能。
華夏公益教科書