继承Ada中的两种类型

时间:2012-01-17 14:09:45

标签: generics inheritance parent-child ada

假设我有:

GENERIC
   TYPE Item IS PRIVATE;
   PACKAGE Abstract_something IS
      TYPE something IS ABSTRACT TAGGED LIMITED PRIVATE;
      procedure x(...)IS ABSTRACT;
      procedure y(...)IS ABSTRACT;
      PRIVATE
         TYPE something IS ABSTRACT TAGGED LIMITED NULL RECORD;
END Abstract_something;
然后我生了两个孩子

1

GENERIC
   PACKAGE Abstract_something.Child IS
      TYPE something_2  IS ABSTRACT NEW something WITH PRIVATE;
      PROCEDURE x(...);
      PROCEDURE y(...);
      FUNCTION  xx(...) RETURN whatever1;
      error: EXCEPTION;
      PRIVATE
         TYPE something_2  IS ABSTRACT NEW something WITH RECORD
            some declarations here..
         END RECORD;
END Abstract_something.Child;

2

GENERIC
PACKAGE Abstract_something.Child2 IS
   TYPE something3 IS ABSTRACT NEW something WITH PRIVATE;
   PROCEDURE z ( ... ) IS ABSTRACT;
   PRIVATE
      TYPE something3 IS ABSTRACT NEW something WITH NULL RECORD;
END Abstract_something.Child2;

这里child和child2都继承自同一个父,我想创建child3 类型为something4,与something2相同,并从中添加过程Z. something3。 能做到吗?怎么样?

感谢。

2 个答案:

答案 0 :(得分:1)

Ada不支持多重继承,但Ada 2005中的“Interfaces”除外,但它没有关联的类型。根据您的编写,您可以通过创建something3的接口来使用该概念(无论如何它都有一个空记录,即使您没有在您的示例中公开它)。

something3真的需要从Abstract_something继承吗?如果没有,你可以做

type something3 is interface;
type something4 is new something2 and something3 with private; -- or with null record etc

根据我的经验,仔细思考手头问题的属性究竟是什么(与实现的问题相反)是值得的:在继承的情况下,整个过程中是否存在“is-a”关系层次?也就是说,当B和C继承自A,而D继承自B和C时,每个B和C也是A?每个D真的都是B和C吗? “Has-a”不适合继承(虽然粗心大意可能会这样实现)。

答案 1 :(得分:0)

您可以使用正交继承,它可能适用于您的用例。您必须将Child2更改为:

GENERIC
   TYPE base IS ABSTRACT NEW something WITH PRIVATE;
PACKAGE Abstract_something.Child2 IS
   TYPE something3 IS ABSTRACT NEW base AND something3_interface WITH PRIVATE;
   PROCEDURE z ( ... ) IS ABSTRACT;
   PRIVATE
      TYPE something3 IS ABSTRACT NEW base AND something3_interface WITH NULL RECORD;
END Abstract_something.Child2;

现在,something3中的添加内容可以应用于从something继承的任何类型 - 您只需要使用要继承的Abstract_something.Child2来实例化base - 比如说something_2

something3_interface是可选的,必须添加到Abstract_something

...
TYPE something3_interface IS INTERFACE;
-- Possibly some primitive operations defined by something3_interface here
...

只有当你想在某个地方使用something3_interface类型而不指定something3的实例化时,你需要接口Abstract_something.Child2 - 因为它的通用包有一个自己的参数,你不能使用{ {1}}直接位于something3之外。