Ada-如何初始化包含File_Type成员的有限标记类型?

Wos*_*ame 3 oop syntax inheritance ada

在以下代码中,Mix_Card_Reader继承自Mix_IO_Device,后者是抽象的标记记录。

以前它包含一个Positive和两个Stream_Access成员。我想更改代码,以便File_Type改为使用成员。

这样做的原因是,我希望这种类型的每个实例都能够在需要时打开和关闭其文件,或者在需要时完全不打开。

问题是我无法初始化此继承类型,因为File_Type它是有限类型。如何编写我的Create_Mix_Card_Reader函数以允许这样做?

.ads ...

   type Mix_IO_Device is abstract tagged limited
      record
         Block_Size : Positive;
         Input_File : File_Type;
         Output_File : File_Type;
      end record;

   type Mix_Card_Reader is new Mix_IO_Device with null record;
Run Code Online (Sandbox Code Playgroud)

.adb ...

   function Create_Mix_Card_Reader return Mix_IO_Device_Access is
      Ret : Mix_IO_Device_Access := new Mix_Card_Reader'(16, null, null);
   begin
      return Ret;
   end Create_Mix_Card_Reader;
Run Code Online (Sandbox Code Playgroud)

GNAT抱怨我不能传递null, null给这对File_Type成员,因为它们当然是不兼容的,空值是以前拥有Stream_Access成员时的遗留物。似乎我必须在这里传递一些信息,但是我不想过早地打开文件只是为了使编译器满意。

该怎么办?

编辑:我有几个明显的选择:

  • 使用access File_Type代替(但我仍然必须在其他位置保持文件的打开/关闭)。
  • 将所有File_Type对象分别存储在一个数组中,并像以前一样使用Streams引用它们,但这似乎很麻烦。

fly*_*lyx 7

这应该可以解决问题:

function Create_Mix_Card_Reader return Mix_IO_Device_Access is
   Ret : Mix_IO_Device_Access := new Mix_Card_Reader'(
     16, Input_Type => <>, Ouptut_Type => <>);
begin
   return Ret;
end Create_Mix_Card_Reader;
Run Code Online (Sandbox Code Playgroud)

框符号是默认值的占位符。您至少需要Ada 2005才能在聚合中使用它,并且不得使用位置表示法,有关详细信息,请参见Ada 2005基本原理。如果需要,可以将两个分配缩短为others => <>