是否可以在fortran中使用类型构造函数中的指针?

abb*_*bot 3 constructor fortran pointers fortran90 fortran95

在一些Fortran 95代码中,我有一个带指针字段的类型.我想声明一个模块变量type(foo)在编译时初始化.像这样的东西:

module foo_module
  implicit none
  type foo_type
     integer :: x
     logical, pointer :: x_flag => null()
  end type foo_type

  logical, target :: bar_flag
  ! this does not compile of course:
  type(foo_type) :: bar = foo_type(1, bar_flag)
end module foo_module
Run Code Online (Sandbox Code Playgroud)

上面的代码片段无法编译.我知道我可以bar在运行时使用单独的子例程进行初始化,例如:

module foo_module
  implicit none
  type foo_type
     integer :: x
     logical, pointer :: x_flag => null()
  end type foo_type

  logical, target :: bar_flag
  type(foo_type) :: bar
contains
  subroutine init()
    bar%x = 1
    bar%x_flag => bar_flag
  end subroutine init
end module foo_module
Run Code Online (Sandbox Code Playgroud)

但是没有初始化子程序可以做到这一点吗?或者是否可以声明由编译器显式调用的初始化子例程?注意:这必须在Fortran 95中完成.

Ian*_*anH 6

初始化程序(在示例代码的第一个块中的bar声明中等于之后出现的东西)必须是初始化(常量)表达式.Fortran 95中的初始化表达式规则不允许结构构造函数中的NULL()以外的指针目标.

(在Fortran 2008中放宽了这条规则,允许初始化表达式中结构构造函数中的指针目标成为具有save属性的变量.)

请注意,init子例程可以使用结构构造函数,而不是分配给各个组件.使用该模块的客户端代码也可以使用结构构造函数直接执行对bar的赋值:bar = foo_type(1, bar_flag).问题不是在结构构造函数中使用指针目标 - 它是结构构造函数中指针目标的外观,它必须是初始化表达式.

无法为派生类型声明初始化过程.(在Fortran 2003中有可能有一个覆盖结构构造函数的函数,但这样的函数不能用在初始化表达式中.)