Fortran派生类型的“初始”语句/自动构造函数

时间:2018-10-05 10:02:02

标签: constructor fortran

我想知道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站点上找到了一些很有希望的信息,但没有其他地方:它使用声明为initial,pass :: classname_ctor0的类型绑定过程指定了类似构造函数的机制。这是什么标准?版本16中的ifort无法编译此处发布的示例,并且我没有可用的标准。

1 个答案:

答案 0 :(得分:4)

与最终子例程不同,“初始”子例程不是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]

这自然与具有“初始”形状的可分配数组组件不同,但是,如果您只希望该组件成为运行时初始可自定义的形状,就足够了。

相关问题