跳轉到內容

Ada 程式設計/屬性/'Pos

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

Ada. Time-tested, safe and secure.
Ada. 經得起時間考驗,安全可靠。

'Pos 屬性定義在所有離散型別上。它是一個函式,返回引數的索引號作為通用整數; 字首 S 必須是子型別名稱。(通用整數被隱式轉換為任何特定整型,這取決於上下文。)

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

對於列舉型別,索引號從 0 開始; 如果引數不代表有效的值(可能是由於未初始化的變數),則會引發 Program_Error 異常。對於整型,屬性返回轉換為通用整數的值。請注意,實際引數不必屬於子型別 S。

請注意,表示子句不會影響索引編號。無論列舉值的底層值是什麼,索引號將保持不變。

I: Integer := -30;

pragma Assert (Integer'Pos(I) = -30);  -- of type universal_integer

type My_Enum is  (Enum1, Enum2, Enum3);
for  My_Enum use (Enum1 => 2, Enum2 => 4, Enum3 => 6);
...
pragma Assert (My_Enum'Pos(Enum1) = 2);  -- Wrong, 2 is the internal representation, not the position
pragma Assert (My_Enum'Pos(Enum1) = 0);  -- Right
pragma Assert (My_Enum'Pos(Enum3) = 2);

subtype My_Enum_Sub is My_Enum range Enum1 .. Enum2;

pragma Assert (My_Enum_Sub'Pos (Enum3) = 2);  -- Enum3 does not belong to My_Enum_Sub

另一個沒有表示子句的示例

  type Color is  (Red, Blue, White);
  Object : Color := White;
begin 
  Put (Color'Pos (Object)); -- prints 2, position of White.
...

另請參閱

[編輯 | 編輯原始碼]

'Pos 屬性的逆運算子是 'Val

可以使用 Unchecked_Conversion 或使用實現定義的屬性 'Enum_Rep(GNAT)獲得底層表示。

有關通用整數的詳細解釋,請參閱 型別系統: 有符號整型的型別詳細討論。

華夏公益教科書

[編輯 | 編輯原始碼]

Ada 參考手冊

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