gpt4 book ai didi

arrays - Ada 中的数组是协变的吗?

转载 作者:行者123 更新时间:2023-12-04 17:39:16 25 4
gpt4 key购买 nike

我知道在 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 协变中的数组吗?

最佳答案

我认为“动物 [] [是] 狗 [] 的父类(super class)型”是指 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

( AnimalDog 对象大小不同)。你可以试试
type Access_Array is array (Positive range <>) of access Animal'Class;

这让你可以说
AA : Access_Array := (1 => new Animal, 2 => new Dog);

但是随后您会遇到内存管理问题,因为 Ada 不进行垃圾收集(至少,使用我知道的任何 native 代码编译器)。您可以使用 Ada.Containers.Indefinite_Vectors 来避免很多悲伤。 .

关于arrays - Ada 中的数组是协变的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8144750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com