【发布时间】:2018-06-08 08:42:31
【问题描述】:
我有以下代码,其中包含一个抽象类型、继承类型和一个简短的程序,我在其中创建一个对象并将其存储在一个数组中。
module m
implicit none
type :: container
class(a), allocatable :: item
end type container
type, abstract :: a
integer, public :: num
end type a
type, extends(a) :: b
integer, public :: num2
end type b
end module m
program mwe
use m
implicit none
class(a), allocatable :: o1
class(container), allocatable :: arr(:)
o1 = b(1, 2)
allocate(arr(2))
arr(1) = container(o1)
select type(t => o1)
type is(b)
write(*,*) t%num, t%num2
end select
select type(t => arr(1)%item)
type is(b)
write(*,*) t%num, t%num2
end select
end program mwe
问题是,输出看起来像这样:
1 2
1 0
可以看出,存储在数组中的同一个变量使第二个变量无效。为什么会这样?是不是因为数组的类型是a,只包含第一个变量?
我正在用ifort version 18.0.3 编译代码。
【问题讨论】:
-
"arr(1)%item = o1" 适用于 gfortran-8.1, tio.run/… 但原始代码给出“错误:在 (1) 的内在赋值中不可分配的变量不能是多态的”
-
@roygvib,在该链接代码中,您重新排序了派生类型的定义(
container在a之后)。那是因为 gfortran 8 还不支持问题中的顺序吗? -
是的,如果“容器”高于“a”(result with OP's order),gfortran 会给出以下错误(您可以在此处修改代码并按下上方的“运行(>)”按钮 :)
-
有趣,谢谢@roygvib。我读过 gfortran 8 支持“递归可分配组件”(Fortran 2008 功能),所以令我惊讶的是它不接受原始订单。
标签: arrays fortran intel-fortran fortran2008