“initial” statement / automatic constructor for a Fortran derived type

前端 未结 1 1019
故里飘歌
故里飘歌 2020-12-20 20:13

I am wondering if there is a constructor-like mechanism in Fortran for derived types, in such a way, that whenever an instance of a type is created, the constructor is calle

相关标签:
1条回答
  • 2020-12-20 20:47

    An 'initial' subroutine is not, unlike a final subroutine, part of a Fortran standard.

    In a derived type certain components may have initial values, set by default initialization, such as

    type t
      integer :: i=5
    end type t
    type(t) :: x  ! x%i has value 5 at this point
    

    However, allocatable array components (along with some other things) may not have default initialization and always start life as unallocated. You will need to have a constructor or some other way of setting such an object up if you wish the component to become allocated.

    In the case of the question, one thing to consider is the Fortran 2003+ parameterized type:

    type t(n)
      integer, len :: n
      integer val(n)
    end type
    type(t(5)) :: x  ! x%val is an array of shape [5]
    

    This naturally isn't the same this as an allocatable array component with an "initial" shape, but if you just want the component to be run-time initial customizable shape this could suffice.

    0 讨论(0)
提交回复
热议问题