【问题标题】:Definition of a generic record通用记录的定义
【发布时间】:2012-11-18 14:42:49
【问题描述】:

我对通用记录的定义有些问题:

-- ADS File
package Stack is

    -- (generic) Entry
    generic type StackEntry is private;

    -- An array of Entries (limited to 5 for testing)
    type StackEntryHolder is array (0..5) of StackEntry;

    -- Stack type containing the entries, it's max. size and the current position
    type StatStack is
    record                                  -- 1 --
        maxSize : Integer := 5;             -- max size (see above)
        pos : Integer := 0;                 -- current position
        content : StackEntryHolder;         -- content entries
    end record;


    -- functions / procedures

end Stack;

如果我编译这个我得到以下错误(-- 1 --):

泛型类型定义中不允许记录

【问题讨论】:

    标签: generics types record ada


    【解决方案1】:

    我认为您想制作一个通用的,它提供私有类型 StatStack 及其操作。

    【讨论】:

    【解决方案2】:

    我认为您正在寻找更像这样的东西:

    generic 
       type StackEntry is private;
    package Stack_G is
    
       type ReturnCode is (Ok,Stack_Full,Stack_Empty);
    
       -- functions / procedures
       procedure Push (E  : in     StackEntry;
                   RC :    out ReturnCode);
       procedure Pop (E  : out StackEntry;
                  RC : out ReturnCode);
    private
       -- An array of Entries (limited to 5 for testing)
       type StackIndex is new Integer range 1 .. 5;
       type StackEntryHolder is array (StackIndex) of StackEntry;
    
       -- Stack type containing the entries, it's max. size and the current position
       type StatStack is record 
          IsEmpty : Boolean := True;
          Pos : StackIndex := StackIndex'First;-- current position
          Content : StackEntryHolder;          -- content entries
       end record;
    
    end Stack_G;
    
    1. 你不需要 maxSize,你可以从数组属性中得到它 '长度或堆栈索引类型'last。
    2. 我已将堆栈重命名为 stack_g(我的命名约定表示 它是一个通用包)
    3. StackEntry 是泛型的参数,您需要我们 实例化你的堆栈包时。
    4. 我添加了一个堆栈索引类型,在实际中养成习惯 在 Ada 中使用新的类型和子类型,它可以为您节省数小时的时间 稍后。

    【讨论】:

    • 我会使用类型 FullStackIndex range 0 .. 5 并将 StackIndex 设为子类型 range 1 .. FullStackIndex'Last。这样你就可以不用IsEmpty。而且我也不会使用带有Stack 的内部名称......我们已经知道它是关于堆栈的!
    • @SimonWright 我考虑了子类型的想法,但认为它超出了我已经提出的问题的范围!
    • 究竟是什么解决了这个问题!谢谢,现在我明白我做错了什么。仅出于兴趣:为什么您更喜欢ReturnCodeout 参数而不是返回值(函数)?
    • 可能是因为您可以通过这种方式返回值和ReturnCode,还是因为函数只能有in 参数?
    • @ollo 是的,你的第二条评论是的 :)
    【解决方案3】:

    这是因为您编写的代码没有遵循泛型声明的正确语法。您可以在the LRM 中查看其辉煌的 BNF 形式。

    基本上,您必须决定是要声明通用包还是通用例程。猜想你想要的不仅仅是一个通用的子例程,我假设你想要一个包。鉴于它应该看起来像:

    generic {通用正式的东西} {包声明}

    ...其中“{package declaration}”只是一个普通的包声明(但可能使用在通用形式部分声明的东西),而“{generic form stuff}”是一系列通用的声明“客户端将传递给泛型的“正式”参数。

    在您的代码中发生的情况是,编译器看到了神奇的词 generic,并且现在期待在下一个子程序或包声明之前的所有内容都将是通用形式参数。它找到的第一个,同一行上的私有类型声明,就可以了。然而,下一行包含一个完整的记录声明,它看起来根本不像一个通用的形式参数。于是编译器一头雾水,吐出一个错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多