跳轉到內容

Ada 程式設計/屬性/'Val

來自華夏公益教科書,開放的書籍,開放的世界

Ada. Time-tested, safe and secure.
Ada. 經久耐用,安全可靠。

'Val 屬性為所有離散型別定義。它是一個函式,返回 S 基型別的那個值,該值具有引數的位置編號;字首 S 必須是子型別名稱。(任何特定整數型別都隱式轉換為universal_integer。)

function S'Val (Arg: universal_integer) return S'Base;

如果 S 型別中沒有值具有 Arg 的位置編號,則會引發 Constraint_Error 異常

請注意,表示子句不會影響位置編號。列舉值具有什麼底層值,位置編號將保持不變。

-- Declare a discrete type; the compiler will assign the internal representation as 0 .. 2
-- identical to the position numbers.
type My_Enum is (Enum1, Enum2, Enum3);

-- Declare a discrete type and explicitly set the internal representation.
-- Note that the position numbers are still 0 .. 2.
type My_Other_Enum is (Value1, Value2, Value3);
for My_Other_Enum use (Value1 => 2, Value2 => 4, Value3 => 6);

pragma Assert (My_Enum'Val(0) = Enum1);  -- OK
pragma Assert (My_Enum'Val(1) = Enum2);  -- OK
pragma Assert (My_Enum'Val(2) = Enum3);  -- OK

pragma Assert (My_Other_Enum'Val(0) = Value1);  -- OK
pragma Assert (My_Other_Enum'Val(1) = Value2);  -- OK
pragma Assert (My_Other_Enum'Val(2) = Value3);  -- OK

pragma Assert (My_Enum'Val(3)       = Enum3);  -- Wrong
pragma Assert (My_Other_Enum'Val(2) = Value1); -- Wrong
pragma Assert (My_Other_Enum'Val(4) = Value2); -- Wrong
pragma Assert (My_Other_Enum'Val(6) = Value3); -- Wrong

其他示例

type Color is (RED, BLUE, WHITE);
   OBJECT : Color := WHITE;
begin
   Put (Color'Val (1));      -- give BLUE

內部表示只能透過 Unchecked_Conversion 查詢。

另請參閱

[編輯 | 編輯原始碼]

'Val 屬性的逆是 'Pos。

華夏公益教科書

[編輯 | 編輯原始碼]

Ada 參考手冊

[編輯 | 編輯原始碼]
華夏公益教科書