明確的型別轉換運算子:)

C + + 中,可以讓使用語法類似於函式呼叫語法的明確型別轉換。

simple-type-name ( expression-list )

備註

A 簡單型別名稱 後面加上 運算式清單括在括號建構使用指定的運算式所指定型別的物件。下列範例會示範的明確型別轉換成 int 型別:

int i = int( d );

下列範例會使用修改過的版本Point中所定義的類別函式呼叫結果

範例

// expre_Explicit_Type_Conversion_Operator.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
class Point
{
public:
    // Define default constructor.
    Point() { _x = _y = 0; }
    // Define another constructor.
    Point( int X, int Y ) { _x = X; _y = Y; }

    // Define "accessor" functions as
    // reference types.
    unsigned& x() { return _x; }
    unsigned& y() { return _y; }
    void Show()   { cout << "x = " << _x << ", "
                         << "y = " << _y << "\n"; }
private:
    unsigned _x;
    unsigned _y;
};

int main()
{
    Point Point1, Point2;

    // Assign Point1 the explicit conversion
    //  of ( 10, 10 ).
    Point1 = Point( 10, 10 );

    // Use x() as an l-value by assigning an explicit
    //  conversion of 20 to type unsigned.
    Point1.x() = unsigned( 20 );
    Point1.Show();

    // Assign Point2 the default Point object.
    Point2 = Point();
    Point2.Show();
}

Output

x = 20, y = 10
x = 0, y = 0

雖然前面的範例示範如何使用常數的明確型別轉換,在物件上執行這些轉換的運作方式相同的技巧。下列程式碼片段示範:

int i = 7;
float d;

d = float( i );

明確的型別轉換也可以使用 「 轉換 」 語法來指定。先前的範例中,使用轉型語法,重寫為:

d = (float)i;

轉換單一值時,型別轉換和函式樣式轉換會有相同的結果。不過,在函式語法中,您可以指定一個以上的引數進行轉換。這項差異是很重要的使用者定義型別。請考慮Point類別和它的轉換:

struct Point
{
    Point( short x, short y ) { _x = x; _y = y; }
    ...
    short _x, _y;
};
...
Point pt = Point( 3, 10 );

上述的範例中,使用函式樣式轉換,會示範如何將兩個值的轉換 (一個用於 x ,一個用於 y) 為使用者定義的型別Point。

注意事項警告

請小心,使用明確型別轉換,因為它們會覆寫 C++ 編譯器內建型別檢查。

轉型 地轉換成不具型別必須使用標記法 簡單型別名稱 (比方說,指標或參考類型)。轉換為型別,可以用來表示與簡單型別名稱可以寫成任一個表單。請參閱型別規範中 如需有關構成 簡單型別名稱

轉換 (cast) 內的型別定義不正確。

請參閱

參考

後置的運算式

C + + 運算子

運算子優先順序和順序關聯性