Fortran 派生类型实例的用户定义构造函数

Cha*_*ang 5 constructor fortran

这是我关于 Fortran 的第二个问题(我使用 C++,所以请原谅我的思维方式)。

我想在适当的时候在 Fortran 中使用 OOP,也就是说,派生类型。在 C++ 中,您可以使用用户定义的构造函数,例如https://msdn.microsoft.com/en-us/library/s16xw1a8.aspx

在 Fortran 中,情况有所不同。我尝试的第一件事是从这里开始:https : //www.ibm.com/developerworks/community/blogs/b10932b4-0edd-4e61-89f2-6e478ccba9aa/entry/object_oriented_fortran_user_defined_constructors2?lang=en

然后我找到了一些其他的方法来做到这一点。在这里,我列出了一些似乎有效的方法,但我只测试了第一种和第二种方法:

  1. 与他们应该构造的派生类型同名的通用接口,请参阅上面的链接;
  2. 使用类型绑定过程(这甚至不是“传统”构造函数)

    MODULE mymod
      TYPE mytype
        Private
        INTEGER :: x
        CONTAINS
        PROCEDURE, PASS :: init
      END TYPE
    CONTAINS
      SUBROUTINE init(this, i)
        CLASS(mytype), INTENT(OUT) :: this
        INTEGER, INTENT(IN) :: i
        write(*,*) this%x
        IF(i > 0) THEN
          this%x = 1
        ELSE
          this%x = 2
        END IF
        write(*,*) this%x
      END SUBROUTINE init
    END
    PROGRAM test
      USE mymod
      TYPE(mytype) :: y
      CALL y%init(1)
    END PROGRAM
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用静态构造函数或结构构造函数(http://www.lahey.com/docs/lfenthelp/NLMOvUsInvConst.htm)但这似乎不适用于一般的 Fortran http://www.lahey.com/docs/lfenthelp/NLMGSWhatIs .htm

所以我还没有很好地理解在实践中初始化/构造派生类型的最优选和最灵活的方法是什么,特别是当我在开发中使用嵌套派生类型时。我希望我能在一些帮助下组织这个主题。

Vla*_*r F 7

好的,所以我假设您阅读了如何在 Fortran 中覆盖结构构造函数中的答案答案,我将回答您在评论中提出的问题。评论中没有足够的地方来回答这个问题。

您还可以在 Fortran 中创建接受可变数量参数的构造函数。

甚至可以使用每个派生类型默认具有的默认结构构造函数。如果默认初始化一个组件,它在构造函数中是可选的。这同样适用于可分配和指针组件。

对于类型

type t1
  integer :: i = 1
  integer, pointer :: ip => null()
  integer, allocatable :: ap
end type
Run Code Online (Sandbox Code Playgroud)

您可以像调用默认构造函数一样

instance = t1()
Run Code Online (Sandbox Code Playgroud)

它是完全合法的,i将是 1,ip将指向null并且ap不会被分配。

或者你可以称之为

 instance = t1(ap=5)
Run Code Online (Sandbox Code Playgroud)

并且该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
Run Code Online (Sandbox Code Playgroud)

任何类型绑定的过程当然也可以有可选参数。


至于嵌套类型,最好将构造函数作为函数来完成,无论它们是默认的还是用户定义的:

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.)
Run Code Online (Sandbox Code Playgroud)