我想了解如何在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