元素数组中的多态性 [英] Polymorphism in an array of elements
问题描述
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屋!