jbe*_*rid 5 arrays ada covariant
我知道在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>
Run Code Online (Sandbox Code Playgroud)
我的问题是Ada Covariant中的数组?
我认为通过"动物[] [是]超类型的狗[]"你的意思是Animal[42]实际上可能是一个Dog?如果是这样,那么答案是否定的.
在Java中,变量(包括数组元素)实际上是引用(想想指针).
特定
type Animal is tagged null record;
type Dog is new Animal with null record;
Run Code Online (Sandbox Code Playgroud)
你当然可以说
type Plain_Array is array (Positive range <>) of Animal;
Run Code Online (Sandbox Code Playgroud)
但那么所有元素都必须如此Animals.
要在Ada中进行调度,您必须具有要调度的类范围值,因此您可以尝试
type Class_Array is array (Positive range <>) of Animal'Class;
Run Code Online (Sandbox Code Playgroud)
但是编译器会告诉你
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
Run Code Online (Sandbox Code Playgroud)
(Animal和Dog对象的大小不同).你可以试试
type Access_Array is array (Positive range <>) of access Animal'Class;
Run Code Online (Sandbox Code Playgroud)
这让你说
AA : Access_Array := (1 => new Animal, 2 => new Dog);
Run Code Online (Sandbox Code Playgroud)
但是你留下了内存管理问题,因为Ada不做垃圾收集(至少,我知道的任何本机代码编译器).你可以通过使用来节省很多悲伤Ada.Containers.Indefinite_Vectors.
| 归档时间: |
|
| 查看次数: |
343 次 |
| 最近记录: |