Pointers 在fortran中是否可以在类型构造函数中使用指针?
在一些Fortran 95代码中,我有一个带有指针字段的类型。我想声明一个Pointers 在fortran中是否可以在类型构造函数中使用指针?,pointers,constructor,fortran,fortran90,fortran95,Pointers,Constructor,Fortran,Fortran90,Fortran95,在一些Fortran 95代码中,我有一个带有指针字段的类型。我想声明一个类型(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
类型(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
上面的代码段无法编译。我知道我可以在运行时使用单独的子例程初始化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
但是,在没有初始化子例程的情况下,有可能做到这一点吗?或者可以声明编译器显式调用的初始化子例程吗?注意:这必须在Fortran 95中完成。初始值设定项(在示例代码的第一块中,在bar声明中出现在等于之后的内容)必须是一个初始化(常量)表达式。Fortran 95中初始化表达式的规则不允许在结构构造函数中使用除NULL()以外的指针目标
(在Fortran 2008中放宽了该规则,以允许初始化表达式中的结构构造函数中的指针目标是带有save属性的变量。)
请注意,您的init子例程可以使用结构构造函数,而不是分配给各个组件。使用该模块的客户端代码还可以使用结构构造函数直接执行对bar的赋值:bar=foo\u type(1,bar\u标志)
。问题不是在结构构造函数中使用指针目标,而是指针目标在结构构造函数中必须是初始化表达式的位置的外观
无法为派生类型声明初始化过程。(在Fortran 2003中,可以使用重写结构构造函数的函数,但这种函数不能用于初始化表达式。)感谢您的精彩解释。仅限于Fortran 95语言子集确实很糟糕:(