我知道在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中的数组是协变的吗?
发布于 2011-11-16 17:41:10
我想“动物是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,您可以为自己节省很多痛苦。
https://stackoverflow.com/questions/8144750
复制相似问题