不能在记录中使用记录的判别

时间:2014-12-03 08:21:09

标签: record ada

我的代码如下。编译器不允许我使用判别式var来控制字符串name的大小。

procedure p is

   type int is range 1 .. 10;
   type my (var : int) is record
      name : string (1 .. var); -- this var here is bad, why?
   end record;

   hh : my(6);

begin
   put (hh.name);
end p;

错误消息是

p.adb:4:23: expected type "Standard.Integer"
p.adb:4:23: found type "int" defined at line 2

1 个答案:

答案 0 :(得分:3)

这是由于Ada强力打字。 Ada允许您声明彼此不兼容的新整数和浮点类型。最初的目的是防止意外使用具有一个含义的值,就好像它们具有完全不相关的含义,例如

type Length is digits 15;  -- in meters
type Mass is digits 15;    -- in kilograms
L : Length;
M : Mass;

M := L;   -- error, caught at compile time

编译器捕获这个没有任何意义的陈述,因为" mass"变量不能保持长度。如果所有内容都只是FloatLong_Float,编译器将无法捕获它。

您所做的是创建另一个整数类型int。如上例所示,新类型的值无法自动转换为Integer,这是String索引的类型。 (String实际上定义为array (Positive range <>) of Character with Pack;,但PositiveInteger子类型,值可以在{{1}之间自动转换}和Positive因为它们实际上是相同基类型的子类型。)

不幸的是,这也是不允许的:

Integer
由于Ada规则,判别式必须单独出现在此上下文中。因此,您唯一的选择是将type my(var : int) is record name : string (1 .. Integer(var)); -- this var here is bad why? end record; 设为子类型:

int