我想了解如何在Ada中使用私人申明,并了解包装。我尽量保持我的代码尽可能短。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
):
我直接用
Rectangular_Form.Vector_Basis_r (A => Theta, D => Basis_r);
,并通过只使用
Rectangular_Form.Get_Horz (Basis_r)
和
Rectangular_Form.Get_Vert (Basis_r)
这似乎稍后访问水平和垂直分量越来越组件A.Horz
和A.Vert
好的,因为我使用的方法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:该功能为省略了和Get_Vert
以使代码缩短。
非常感谢...
@ Marc C谢谢。这是让我困惑的部分。所以,你的意思是''程序Vector_Basis_r'已经在'Rectangular'定义之后的'Rectangular_Method_1.ads'中被定义了,所以这就是为什么我不需要'set'方法? 1 vote up – yCalleecharan
@yCalleecharan - 扩展我的答案... –
不,可以有多个相同规范的实现;在编译时选择所需的身体。这应该是一个单独的问题,重点在于什么是不同的。 – trashgod