“初始"Fortran 派生类型的语句/自动构造函数 [英] "initial" statement / automatic constructor for a Fortran derived type

查看:31
本文介绍了“初始"Fortran 派生类型的语句/自动构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 Fortran 中是否有类似构造函数的机制用于派生类型,这样每当创建类型的实例时,构造函数就会自动调用.我阅读了 this 问题,但我并不满意.

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 called automatically. I read this question, but it was unsatisfactory to me.

完整性示意图:

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) 而无需任何额外的 在手动添加的代码中调用array(instance).

Now when I create an instance of type(array) :: instance I'd like the constructor array(instance) to be called automatically without any extra call array(instance) in the code added manually.

我在 this 网站上找到了一些有希望的信息,但在其他地方没有:它指定了一个类似于构造函数的机制,其中类型绑定过程声明为 initial,pass :: classname_ctor0.这是什么标准?版本 16 中的 ifort 不会编译那里发布的示例,并且我没有可用的标准.

I found some promising information on this site, but nowhere else: It specifies a constructor-like mechanism with the type-bound procedure declared initial,pass :: classname_ctor0. What standard is this? ifort in version 16 won't compile the example posted there and I have no standard available.

推荐答案

与最终子例程不同,初始"子例程不是 Fortran 标准的一部分.

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.

就问题而言,要考虑的一件事是 Fortran 2003+ 参数化类型:

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.

这篇关于“初始"Fortran 派生类型的语句/自动构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆