Ada:操作私有类型

我对 Ada 有点陌生,最近遇到了一个我似乎不知道如何解决的错误。

我有以下代码:

数据广告

    with Text_IO; use text_io;
with ada.Integer_Text_IO; use ada.Integer_Text_IO;

package data is

type file is private;

   type file_set is array (Integer range <>) of file;
   procedure file_Print (T : in out file); --Not used

private
type file is record
      start, deadline : integer;
end record;

end data;

主文件

with ada.Integer_Text_IO; use ada.Integer_Text_IO;


procedure Main is

   Num_files: integer:=3; 
  
   Files:file_set(1..Num_files);
     
begin
   
Files(1):=(2,10); -- Expected private type "file" defined at data.ads

for i in 1..Num_Files loop
      
      Put(integer'Image(i));
      New_Line;
      data.File_Print(Files(i));

但我收到此错误在 data.ads 中定义的预期私有类型“文件”
如何访问文件类型并在 main 中声明一个新的值数组?

回答

没错 - 您无法查看或操作私有类型中的内容。那将破坏封装。错误和安全风险随之而来。

您只能通过其方法与私有类型交互:在声明它的包中声明的函数和过程。

现在 file_set 不是私有类型(您可能会考虑稍后将其设为私有,以便更好地封装,但现在....)您可以索引它以访问其中的文件(使用这些过程之一)。

Files(1):=(2,10);

由于您想在此处创建文件,因此您需要一种创建文件的方法……有点类似于 C++ 中的构造函数,但实际上更像对象工厂设计模式。将此添加到包中:

   function new_file(start, deadline : integer) return file;

并在包体中实现:

package body data is

    function new_file(start, deadline : integer) return file is
    begin
       -- check these values are valid so we can guarantee a proper file
       -- I have NO idea what start, deadline mean, so write your own checks!
       -- also there are better ways, using preconditions in Ada-2012
       -- without writing explicit checks, but this illustrates the idea
       if deadline < NOW or start < 0 then 
          raise Program_Error;
       end if;
       return (start => start, deadline => deadline);
    end new_file;

    procedure file_Print (T : in out file) is ...

end package body;

这给了你的包的用户写权限

Files(1):= new_file(2,10);
Files(2):= new_file(start => 3, deadline => 15);

但如果他们试图制造垃圾来利用你的系统

Files(3):= new_file(-99,-10);     -- Oh no you don't!

这是创建文件的唯一方法,因此他们无法绕过您的检查。


以上是Ada:操作私有类型的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>