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

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

问题描述

我想知道Fortran中是否存在用于派生类型的类似于构造函数的机制,以这种方式,每当创建类型的实例时,都会自动调用该构造函数。我阅读了这个问题,但这对我来说并不令人满意。

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)::实例的实例我希望自动调用构造函数 array(instance),而无需在其中添加任何 call 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.

我在网站,但没有其他地方:它指定了类似构造函数的机制声明为 initial,pass :: classname_ctor0 的类型绑定过程的ism。这是什么标准?版本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天全站免登陆