元素数组中的多态性 [英] Polymorphism in an array of elements

查看:184
本文介绍了元素数组中的多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经定义了一个名为 geometry 的派生类型(在Fortran 2003中),我将它扩展为两个新派生类型: circle 三角形。每个扩展类型都有自己的构造函数, NewCircle NewTriangle 返回一个 circle 对象和一个三角形对象。



然后我想这样做:

 使用appropriate_module 
class(geometry),allocatable :: Geo(:)
allocate(Geo(2))
Geo(1)= NewCircle
Geo(2)= NewTriangle

当然,最后两行在Fortran 2003标准中是无效的。
我不想创建封装在派生类型中的指针数组来链接不同类型的对象,因为对象需要在数组中链接之前创建。在上面的(假设的)情况下,对象将被立即创建并存储在数组中。



任何建议都可以这样做,还是限制语言?

解决方案

如果您需要值语义,请使用多态可分配组件创建一个派生类型数组。 b

 使用appropriate_module 
类型geometry_element
类(几何),allocatable :: item
结束类型geometry_element

类型(geometry_element),allocatable :: geo(:)
geo = [geometry_element(NewCircle()),&
geometry_element(NewTriangle())]

如果新的几何使用可分配参数(而不是通过函数结果)将对象传递回调用作用域,那么 MOVE_ALLOC 内部函数提供了一种高效的将构造的值移动到数组的元素中。


Suppose I have defined a derived type (in Fortran 2003) named geometry and I extend it to two new derived types: circle and triangle. Each extended type has its own constructor, NewCircle and NewTriangle that returns a circle object and a triangle object respectively.

Then I would like to do this:

use appropriate_module
class(geometry), allocatable :: Geo(:)
allocate(Geo(2))
Geo(1) = NewCircle
Geo(2) = NewTriangle

Of course the last two lines are invalid in Fortran 2003 standard. I do not want to create an array of pointers encapsulated in a derived type to link object of different type because the objects need to be created before being linked in the array. In the above (hypothetical) case, the objects would be created and stored in the array immediately.

Any suggestion to do it, or is it a limitation of the language?

解决方案

If you want value semantics, create an array of derived type with a polymorphic allocatable component.

use appropriate_module
type geometry_element
  class(geometry), allocatable :: item
end type geometry_element

type(geometry_element), allocatable :: geo(:)
geo = [ geometry_element(NewCircle()),  &
        geometry_element(NewTriangle()) ]

If a new geometry object was passed back to the calling scope using an allocatable argument (rather than via a function result), then the MOVE_ALLOC intrinsic provides an efficient way of moving the constructed value into an element of the array.

这篇关于元素数组中的多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆