跳轉到內容

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

50% developed
華夏公益教科書,自由的教學讀物

第五課:型別轉換

[編輯 | 編輯原始碼]

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

示例程式碼

[編輯 | 編輯原始碼]
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) 來實現此操作。

  • 您不能使用強制型別轉換將整數轉換為字串(反之亦然)。有一個庫函式,您將在稍後學習如何使用它來完成此操作。
華夏公益教科書