在这里值得注意的是,尽管根据原有的代码实例,定义BOX为一个limited类型的,但是我们知道limited关键字修饰的类型定义的对象,是不允许进行赋值以及其他的比较操作的,所以,原有的教程出现了纰漏,这里进行修正。
shape.ads
package Shape is
type BOX is -- limited
record
Length : INTEGER;
Width : INTEGER;
Height : INTEGER;
end record;
-- function Make_A_Box(In_Length, In_Width, In_Height : INTEGER)
-- return BOX;
procedure Make_A_Box(Result_Box : out BOX;
In_Length, In_Width, In_Height : INTEGER);
function "="(Left, Right : BOX) return BOOLEAN;
function "+"(Left, Right : BOX) return BOX;
procedure Print_Box(Input_Box : BOX);
end Shape;
shape.adb
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
package body Shape is
procedure Make_A_Box(Result_Box : out BOX;
In_Length, In_Width, In_Height : INTEGER) is
begin
Result_Box.Length := In_Length;
Result_Box.Width := In_Width;
Result_Box.Height := In_Height;
end Make_A_Box;
function "="(Left, Right : BOX) return BOOLEAN is
begin
if (Left.Length = Right.Length and
Left.Width = Right.Width and
Left.Height = Right.Height) then
return TRUE;
else
return FALSE;
end if;
end "=";
function "+"(Left, Right : BOX) return BOX is
Temp_Box : BOX;
begin
Temp_Box.Length := Left.Length + Right.Length;
Temp_Box.Width := Left.Width + Right.Width;
Temp_Box.Height := Left.Height + Right.Height;
return Temp_Box;
end "+";
procedure Print_Box(Input_Box : BOX) is
begin
Put("Length = ");
Put(Input_Box.Length, 3);
Put(" Width = ");
Put(Input_Box.Width, 3);
Put(" Height = ");
Put(Input_Box.Height, 3);
New_Line;
end Print_Box;
end Shape;
main.adb
with Ada.Text_IO, Shape;
use Ada.Text_IO;
use type Shape.BOX;
procedure OperOver is
Small_Box : Shape.BOX;
Big_Box : Shape.BOX;
begin
-- Small_Box := Shape.Make_A_Box(2, 3, 2);
-- Big_Box := Shape.Make_A_Box(4, 5, 3);
Shape.Make_A_Box(Small_Box, 2, 3, 2);
Shape.Make_A_Box(Big_Box, 4, 5, 3);
Shape.Print_Box(Small_Box);
Shape.Print_Box(Big_Box);
if Small_Box = Small_Box then
Put_Line("The small box is the same size as itself.");
else
Put_Line("The small box is not itself.");
end if;
if Small_Box /= Big_Box then
Put_Line("The boxes are different sizes.");
else
Put_Line("The boxes are the same size.");
end if;
end OperOver;