105.关于limited关键字的一个有用的例子

在这里值得注意的是,尽管根据原有的代码实例,定义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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值