5

我知道在 Java 中数组是协变的。例如:

Assume Dog is a subclass of Animal
In java the arrays are covariant making: Animal[] a supertype of Dog[]
But in java generic collections are not covariant such as: 
ArrayList<Animal> is not a supertype of ArrayList<Dog>

我的问题是 Ada Covariant 中的数组吗?

4

1 回答 1

9

我认为“Animal [] [是] Dog [] 的超类型”你的意思是它Animal[42]实际上可能是一个Dog?如果是这样,那么答案是否定的。

在 Java 中,变量(包括数组元素)实际上是引用(想想指针)。

给定

type Animal is tagged null record;
type Dog is new Animal with null record;

你当然可以说

type Plain_Array is array (Positive range <>) of Animal;

但是所有的元素都必须是Animals

要在 Ada 中调度,你必须有一个类范围的值才能调度,所以你可以尝试

type Class_Array is array (Positive range <>) of Animal'Class;

但是编译器会告诉你

gnatmake -c -u -f covariant_arrays.ads
gcc -c covariant_arrays.ads
covariant_arrays.ads:8:59: unconstrained element type in array declaration
gnatmake: "covariant_arrays.ads" compilation error

Animal并且Dog对象的大小不同)。你可以试试

type Access_Array is array (Positive range <>) of access Animal'Class;

这让你可以说

AA : Access_Array := (1 => new Animal, 2 => new Dog);

但是随后您会遇到内存管理问题,因为 Ada 不进行垃圾收集(至少,对于我所知道的任何本机代码编译器)。您可以使用Ada.Containers.Indefinite_Vectors.

于 2011-11-16T09:41:09.987 回答