1

我对通用记录的定义有些麻烦:

-- 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;

如果我编译它,我会收到以下错误(at -- 1 --):

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

4

3 回答 3

4

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

于 2012-11-18T14:55:02.220 回答
3

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

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,您可以从数组属性“长度或堆栈索引类型”最后获取。
  2. 我已将堆栈重命名为 stack_g(我的命名约定表明它是一个通用包)
  3. StackEntry 是泛型的参数,在实例化堆栈包时需要使用它。
  4. 我添加了一个堆栈索引类型,在实践中养成在 Ada 中使用新类型和子类型的习惯,它可以为您节省数小时后的时间。
于 2012-11-18T21:23:10.127 回答
3

That's because the code you wrote doesn't follow the proper syntax for a generic declaration. You can view this in its glorious BNF form in the LRM.

Basically, you have to decide if you want to declare a generic package or a generic routine. Guessing you want more that just a single subroutine generic, I'll assume you want a package. Given that it should look something like:

generic {generic formal stuff} {package declaration}

...where "{package declaration}" is just a normal package delcaration (but one that may use stuff declared in the generic formal part), and "{generic formal stuff}" is a series of delcarations of generic "formal" parameters that the client will pass into the generic.

What happened in your code is that the compiler sees the magic word generic and is now expecting everything up until the next subprogram or package delcaration will be generic formal parameters. The first one it finds, the private type delcaration on the same line, is just fine. However, the next line contains a full record declaration, which doesn't look like a generic formal parameter at all. So the compiler got confused and spit out an error.

于 2012-11-19T15:17:51.597 回答