Ada:变体记录,其中一部分案例共享一个共同属性

web*_*rc2 2 ada

我有以下代码,我只想在前两个案例中共享一个共同的属性; 但是,"id" conflicts with the declaration at line 11当我尝试使用此语法时,我收到错误:

   type Shape (Which : Shape_Type := SQUARE) is
      record
      case Which is
         when Square =>
            id : Natural;   -- Line 11
         when Turnout =>
            id : Natural;   -- Line that causes error to be thrown
         when Invalid =>
            null;
      end case;
      end record;
Run Code Online (Sandbox Code Playgroud)

Sim*_*ght 5

这个:

type Shape (Which : Shape_Type := SQUARE) is
   record
      case Which is
         when Square | Turnout =>
            id : Natural;
         when Invalid =>
            null;
      end case;
   end record;
Run Code Online (Sandbox Code Playgroud)

如果您以后希望Turnout案例具有额外属性,则可以使用嵌套case(但仍需要涵盖所有备选方案):

type Shape (Which : Shape_Type := SQUARE) is
   record
      case Which is
         when Square | Turnout =>
            id : Natural;
            case Which is
               when Square =>
                  null;
               when Turnout =>
                  Deg : Natural;
               when Invalid =>
                  null;
            end case;
         when Invalid =>
            null;
      end case;
   end record;
Run Code Online (Sandbox Code Playgroud)