You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Mac Intel的GNAT CE中,如何正确用Ada定义带未限定整数字段的记录?

Ada记录类型中定义可后续约束的整数字段

错误写法分析

你提供的代码存在两处语法错误:

  • num: Integer positive range <>;:语法混乱,Positive本身就是Integer的预定义子类型,无需重复声明Integer;且直接在记录字段中使用range <> (未限定范围)不符合Ada语法,记录字段必须绑定具体类型。
  • position: Integer range <> ) of integer;:存在多余的) of integer,完全违反Ada类型声明语法。

正确实现方式

要实现“记录字段初始为未限定状态,后续通过<>指定范围”的需求,需借助泛型记录类型,将字段的整数范围作为泛型参数延迟定义:

-- 在.ads文件中定义泛型记录
generic
   -- 定义两个未限定的整数子类型参数,后续实例化时指定具体范围
   type Gear_Num_Type is range <>;
   type Gear_Position_Type is range <>;
type A_Gear is record
   Num : Gear_Num_Type;
   Position : Gear_Position_Type;
end record;

实例化与使用

在需要使用该记录的地方,通过<>传入具体的范围约束来实例化泛型记录:

-- 实例化时指定Num为1-10的正整数,Position为-5到5的整数
package Car_Gear_Instance is new A_Gear(
   Gear_Num_Type => Positive range 1..10,
   Gear_Position_Type => Integer range -5..5
);

-- 使用实例化后的记录类型
My_Car_Gear : Car_Gear_Instance.A_Gear := (Num => 3, Position => 0);

简化场景(字段范围一致)

如果两个字段的范围约束逻辑一致,可简化泛型参数:

generic
   type Gear_Range is range <>;
type A_Gear is record
   Num : Gear_Range;
   Position : Gear_Range;
end record;

-- 实例化示例
package Bike_Gear_Instance is new A_Gear(Gear_Range => Positive range 1..6);

内容的提问来源于stack exchange,提问作者Michael Ayres

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 14:45:36