首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ada中的数组是协变的吗?

Ada中的数组是协变的吗?
EN

Stack Overflow用户
提问于 2011-11-16 07:43:38
回答 1查看 353关注 0票数 5

我知道在Java中数组是协变的。举个例子:

代码语言:javascript
复制
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中的数组是协变的吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-16 17:41:10

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

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

给定的

代码语言:javascript
复制
type Animal is tagged null record;
type Dog is new Animal with null record;

你当然可以说

代码语言:javascript
复制
type Plain_Array is array (Positive range <>) of Animal;

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

要在Ada中实现分派,必须有一个类范围的值来进行分派,所以可以尝试

代码语言:javascript
复制
type Class_Array is array (Positive range <>) of Animal'Class;

但是编译器会告诉你

代码语言:javascript
复制
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对象的大小不同)。你可以试一试

代码语言:javascript
复制
type Access_Array is array (Positive range <>) of access Animal'Class;

这让你可以说

代码语言:javascript
复制
AA : Access_Array := (1 => new Animal, 2 => new Dog);

但是,您将面临内存管理问题,因为Ada不执行垃圾收集(至少,对于我所知道的任何本机代码编译器而言)。通过使用Ada.Containers.Indefinite_Vectors,您可以为自己节省很多痛苦。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8144750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档