我想知道 Fortran 中是否有类似构造函数的派生类型机制,这样,每当创建类型的实例时,就会自动调用构造函数。我读了this问题,但这对我来说并不令人满意。
完整性示意图示例:
module mod
integer :: n=5
type array
real, dimension(:), allocatable :: val
contains
procedure :: array()
end type
subroutine array(this)
allocate(this%val(n))
end subroutine
end module
现在,当我创建
type(array) :: instance
的实例时我想要构造函数 array(instance)
无需任何额外的 call array(instance)
即可自动调用在手动添加的代码中。我在 this 上发现了一些有希望的信息站点,但没有其他地方:它指定了一个类似构造函数的机制,其中声明了类型绑定(bind)过程
initial,pass :: classname_ctor0
.这是什么标准? ifort
在版本 16 中不会编译那里发布的示例,并且我没有可用的标准。
最佳答案
与最终子例程不同,“初始”子例程不是 Fortran 标准的一部分。
在派生类型中,某些组件可能具有初始值,由默认初始化设置,例如
type t
integer :: i=5
end type t
type(t) :: x ! x%i has value 5 at this point
但是,可分配数组组件(以及其他一些东西)可能没有默认初始化,并且总是以未分配状态开始。如果您希望组件被分配,您将需要有一个构造函数或其他设置此类对象的方法。
在问题的情况下,要考虑的一件事是 Fortran 2003+ 参数化类型:
type t(n)
integer, len :: n
integer val(n)
end type
type(t(5)) :: x ! x%val is an array of shape [5]
这自然与具有“初始”形状的可分配数组组件不同,但如果您只想让组件成为运行时初始可定制形状,这可能就足够了。
关于constructor - "initial"语句/Fortran 派生类型的自动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52663082/