好的,所以我假设您仔细阅读了答案如何在 Fortran 中重写结构构造函数我会回答您在评论中提出的问题。评论中没有足够的地方来回答这个问题。
您还可以在 Fortran 中创建接受可变数量参数的构造函数。
甚至可以使用每个派生类型默认具有的默认结构构造函数。如果默认初始化一个组件,则它在构造函数中是可选的。这同样适用于可分配组件和指针组件。
For type
type t1
integer :: i = 1
integer, pointer :: ip => null()
integer, allocatable :: ap
end type
你可以像这样调用默认构造函数
instance = t1()
而且这是完全合法的,i
将是 1,ip
将指向null
and ap
不会被分配。
或者你可以将其称为
instance = t1(ap=5)
and the ap
组件将被分配并设置为 5,其他组件将保留默认值。
您只需通过传递参数就可以使用用户定义的构造函数实现类似的功能optional
.
function t1_user(ap, i) result(res)
type(t1) :: res
integer, allocatable :: ap !this argument MUST be passed,
! it does not have to be allocated
integer, optional :: i ! this argument is optional
if (present(i)) then
...
end if
end function
任何类型绑定过程当然也可以有可选参数。
至于嵌套类型,最好将构造函数作为函数来完成,无论它们是默认的还是用户定义的:
type inner
real :: x, y
end type
type outer
type(inner), allocatable :: in
real :: z
end type
instance1 = outer(inner(1., 2.), 3.)
instance2 = outer(z=4.)