【问题标题】:How to set up and derive a type from an abstract tagged record?如何从抽象标记记录中设置和派生类型?
【发布时间】:2012-10-15 01:39:01
【问题描述】:

我在理解 Ada 中的继承以及一些语法方面遇到了一些困难。

我的目标是从带有记录的抽象类型派生,并在记录字段中使用不同的数据类型。这是我能够编译的:

type Base is abstract new Parent.ParentType with record
    X:Access_Type;
end record

type Child is new Base with record
    n:Integer;
end record;

但我不想有这个额外的 n 字段,我想让 X 是子类型中的整数。我无法让编译器对此感到满意。我想要的是以下内容:

type Base is abstract new Parent.ParentType with tagged record
    X:Access_Type;
end record;

type Child is new Base with record
    X:Integer;
end record;

不幸的是,我不知道如何标记我认为允许我重新分配 X 字段的基本类型。 (没有标记,编译器会抱怨声明冲突。)

有人可以解释一下吗?总的来说,我对 OO 编程很陌生,我发现 Ada 的类型方法比通常的类方法更令人困惑。

【问题讨论】:

    标签: ada


    【解决方案1】:

    你确定你不只是想嵌套一些记录吗?

       type Base is abstract new Parent.Parent_Type with record
          X : Float;
       end record;
    

    ...

    type child_rec is 
      X : integer;
    end record;
    

    ...

       type Child is new Bases.Base with record
          C : Child_Rec;
       end record;
    

    这将允许您参考

    My_Base.X;
    

    My_Base.C.X;
    

    当然,这也可以在没有任何 OO 功能的情况下完成....

    【讨论】:

      【解决方案2】:

      我不确定您要通过更改派生类型中的X 类型来解决什么问题。正如Ada 95 Rationale: II.1 Programming by Extension 中所建议的,标记类型的扩展 组件添加到从基本类型继承的组件中。您可能正在寻找一种使用discriminants 为派生类型指定参数的方法。

      附录:了解 Ada 对常见 object-oriented programming 原则的支持不限于标记类型可能会有所帮助。

      【讨论】:

      • 您可能一直认为Child.X隐藏 Base.X,就像在Java 中但在Ada 中不同;见page 13 of the PDF
      【解决方案3】:

      Base 必须被标记,因为你不能说 is abstract new Parent.Parent_Type 除非 Parent.Parent_Type 被标记,这意味着任何派生类型(例如 Base)也必须被标记。

      问题在于,正如您所拥有的那样,任何可以看到Child 的代码都可以看到两个Xs; Base 中的一个和Child 中的一个。编译器不会让你模棱两可;当其他人阅读您的代码并看到 My_Child.X 时,他们怎么知道您指的是哪个 X

      解决此问题的一种方法是将Base 的完整声明设为私有,这样My_Child.X 只有一种可见的可能性:

      package Bases is
         type Base is abstract new Parent.Parent_Type with private;
      private
         type Base is abstract new Parent.Parent_Type with record
            X : Float;
         end record;
      end Bases;
      
      with Bases;
      package Children is
         type Child is new Bases.Base with record
            X : Integer;
         end record;
      end Children;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-09
        • 2011-02-01
        • 2021-08-04
        • 2018-11-19
        • 2017-04-28
        相关资源
        最近更新 更多