将类型转换为字符串

3
我创建了一个类型:
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" 属性必须是标量类型

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


为了自定义“图像属性”,您需要编写一个函数,该函数接受类型的值并返回字符串。您可能会将此函数称为“Image”。我不明白为什么编写Mytypes.Type_A.Image(Myarray)而不是您尝试的内容会有问题。 - Jeffrey R. Carter
1个回答

5
目前还不可能,但在Ada 202x中将会实现[AI12-0020-1]。在那之前,您需要定义一个子程序(例如Image)并显式调用它。另请参见SO上的此相关问题
使用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;

但是如果没有GNAT.Formatted_String,您也可以使用Ada.Integer_Text_IOCounter_Type'Image等来替代。


1
谢谢,它运行得很好。但是我不理解 +"..."-(...),(我是Ada的新手)。 - A.Pissicat
1
Ada 允许重载运算符(包括一元运算符 +-)。运算符具有强的数学语义。但是 Ada (像大多数语言一样)不强制执行这些语义。您可以自由地给运算符任何(类型相关的)行为/语义。因此,您可以(误用)(重载)特性来定义一个非常短(易于编写)和独特的“名称”的函数。在此示例中,运算符充当执行(类型)转换的函数(请参见 g-forstr.ads)。 - DeeDee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接