我正在尝试学习如何在Ada中使用私有声明以及了解包装。我试图让我的代码尽可能短。
我们从主文件rectangular_Form.ads
with Rectangular_Method_1;
package Rectangular_Form renames Rectangular_Method_1;
-- with Rectangular_Method_2;
-- package Rectangular_Form renames Rectangular_Method_2;
这告诉我们,我们可以有两个实现,现在已经选择了Rectangular_Method_1
。
然后我们有规范文件Rectangular_Method_1.ads
:
package Rectangular_Method_1 is
type Rectangular is private;
procedure Vector_Basis_r (A : in Long_Float; D : out Rectangular);
procedure Set_Horz (R : in out Rectangular; H : Long_Float);
function Get_Horz (R : Rectangular) return Long_Float;
private
type Rectangular is
record
Horz, Vert: Long_Float;
end record;
end Rectangular_Method_1;
及其正文Rectangular_Method_1.adb
:
with Ada.Numerics.Long_Elementary_Functions;
use Ada.Numerics.Long_Elementary_Functions;
package body Rectangular_Method_1 is
procedure Vector_Basis_r (A : in Long_Float; D : out Rectangular) is
begin
D.Horz := Cos (A, Cycle => 360.0);
D.Vert := Sin (A, Cycle => 360.0);
end Vector_Basis_r;
procedure Set_Horz (R : in out Rectangular; H : Long_Float) is
begin
R.Horz := H;
end Set_Horz;
function Get_Horz (R : Rectangular) return Long_Float is
begin
return R.Horz;
end Get_Horz;
end Rectangular_Method_1;
最后是测试脚本:test_rectangular_form.adb
:
with Ada.Long_Float_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with Rectangular_Form;
use type Rectangular_Form.Rectangular;
procedure Test_Rectangular_Form is
Component_Horz, Component_Vert, Theta : Long_Float;
Basis_r : Rectangular_Form.Rectangular;
begin
Ada.Text_IO.Put("Enter the angle ");
Ada.Long_Float_Text_IO.Get (Item => theta);
--Vector basis
Rectangular_Form.Vector_Basis_r (A => Theta, D => Basis_r);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put("rhat_min_theta = ");
Ada.Long_Float_Text_IO.Put (Item => Rectangular_Form.Get_Horz (Basis_r), Fore => 3, Aft => 5, Exp => 0);
Ada.Text_IO.Put(" ihat + ");
Ada.Long_Float_Text_IO.Put (Item => Rectangular_Form.Get_Vert (Basis_r), Fore => 3, Aft => 5, Exp => 0);
Ada.Text_IO.Put (" jhat ");
end Test_Rectangular_Form;
问题(适用于test_rectangular_form.adb
):
我直接使用
获取组件A.Horz
和A.Vert
Rectangular_Form.Vector_Basis_r (A => Theta, D => Basis_r);
稍后使用
访问水平和垂直组件 Rectangular_Form.Get_Horz (Basis_r)
和
Rectangular_Form.Get_Vert (Basis_r)
这似乎没问题,因为我使用方法Get_Horz
和Get_Vert
来访问私有 矩形水平和垂直组件。但是,我直接从命令行读取变量Theta
并使用
Rectangular_Form.Vector_Basis_r (A => Theta, D => Basis_r);
如果矩形组件A.Horz
和A.Vert
是私有的,因为我已经定义了它们,为什么我不必使用方法set_Horz(A)
并set_Vert(A)
先前发出命令
Rectangular_Form.Vector_Basis_r (A => Theta, D => Basis_r);
PS:省略了Set_Vert
和Get_Vert
的功能以保持代码简短。
非常感谢...
答案 0 :(得分:4)
为什么我不必先使用方法set_Horz(A)和set_Vert(A) 发出命令
因为您通过执行
来设置私人记录的字段Rectangular_Form.Vector_Basis_r(A => Theta,D => Basis_r);
(查看Vector_Basis_r的实现。)
- 扩展答案
在Test_Rectangular_Form过程中声明Basis_r变量时,将分配该“Rectangular”变量的内存。此时,私有类型中的Horz和Vert字段存在,但未设置(它们可以包含任何内容)。
当您调用Rectangular_Form.Vector_Basis_r时,其实现会设置这些私有字段的值。也许这让您感到困惑:声明私有类型的包的主体可以直接访问这些字段。这正是Vector_Basis_r在设置它们(以及Set_Vert和Set_Horz)时利用的方面。