将类型转换为字符串

时间:2019-06-28 09:23:12

标签: types ada

我创建了一个类型:

packages MyTypes.Type_A is
    subtype Counter_Type is Integer range 0 .. 15;
    type Array_Counter_Type is record
        Counter_01 : Counter_Type ;
        Counter_02 : Counter_Type ;
        Counter_03 : Counter_Type ;
        Counter_04 : Counter_Type ;
    end record;
end MyTypes.Type_A;

我想这样显示我的数组

MyArray : Array_Counter_Type;
print ( MyTypes.Type_A.Array_Counter_Type'Image (MyArray));

但是我有错误:

  

前缀og“图片”属性必须为标量类型

我该怎么办?是否可以“定制” Image来连接以“-”分隔的4个计数器?

1 个答案:

答案 0 :(得分:5)

这还不可能,但是将在Ada 202x [AI12-0020-1]中使用。在此之前,您将必须定义一个子程序(例如Image)并显式调用它。另请参见this related question

使用GNAT.Formatted_String的示例:

main.adb

with Ada.Text_IO;
with GNAT.Formatted_String;

procedure Main is

   subtype Counter_Type is Integer range 0 .. 15;

   type Array_Counter_Type is
      record
         Counter_01 : Counter_Type;
         Counter_02 : Counter_Type;
         Counter_03 : Counter_Type;
         Counter_04 : Counter_Type;
      end record;

   -----------
   -- Image --
   -----------

   function Image (Array_Counter : Array_Counter_Type) return String is      
      use GNAT.Formatted_String;      
      Format : constant Formatted_String := +"%02d-%02d-%02d-%02d";
   begin      
      return
        -(Format
          & Array_Counter.Counter_01
          & Array_Counter.Counter_02
          & Array_Counter.Counter_03
          & Array_Counter.Counter_04);
   end Image;     

   AC : Array_Counter_Type := (0, 5, 10, 15);

begin
   Ada.Text_IO.Put_Line (Image (AC));
end Main;

但是如果Ada.Integer_Text_IO不可用,您也可以使用Counter_Type'ImageGNAT.Formatted_String等。