gpt4 book ai didi

Ada:操纵私有(private)类型

转载 作者:行者123 更新时间:2023-12-02 02:29:29 25 4
gpt4 key购买 nike

我对 Ada 还不太熟悉,最近遇到了一个错误,我似乎不知道如何解决。

我有以下代码:

数据.ads

    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;

Main.adb

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));

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

最佳答案

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

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

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

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:操纵私有(private)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65270881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com