Ada 程式設計/屬性/'Pos
外觀
'Pos 屬性定義在所有離散型別上。它是一個函式,返回引數的索引號作為通用整數; 字首 S 必須是子型別名稱。(通用整數被隱式轉換為任何特定整型,這取決於上下文。)
functionS'Pos (Arg: S'Base)returnuniversal_integer;
對於列舉型別,索引號從 0 開始; 如果引數不代表有效的值(可能是由於未初始化的變數),則會引發 Program_Error 異常。對於整型,屬性返回轉換為通用整數的值。請注意,實際引數不必屬於子型別 S。
請注意,表示子句不會影響索引編號。無論列舉值的底層值是什麼,索引號將保持不變。
I: Integer := -30;pragmaAssert (Integer'Pos(I) = -30); -- of type universal_integertypeMy_Enumis(Enum1, Enum2, Enum3);forMy_Enumuse(Enum1 => 2, Enum2 => 4, Enum3 => 6); ...pragmaAssert (My_Enum'Pos(Enum1) = 2); -- Wrong, 2 is the internal representation, not the positionpragmaAssert (My_Enum'Pos(Enum1) = 0); -- RightpragmaAssert (My_Enum'Pos(Enum3) = 2);subtypeMy_Enum_SubisMy_EnumrangeEnum1 .. Enum2;pragmaAssert (My_Enum_Sub'Pos (Enum3) = 2); -- Enum3 does not belong to My_Enum_Sub
另一個沒有表示子句的示例
typeColoris(Red, Blue, White); Object : Color := White;beginPut (Color'Pos (Object)); -- prints 2, position of White. ...
'Pos 屬性的逆運算子是 'Val。
可以使用 Unchecked_Conversion 或使用實現定義的屬性 'Enum_Rep(GNAT)獲得底層表示。
有關通用整數的詳細解釋,請參閱 型別系統: 有符號整型的型別詳細討論。
