gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:29:42 24 4
gpt4 key购买 nike

这是我与 Fortran 相关的第二个问题(我使用 C++,请原谅我的思维方式)。
我想在适当的时候使用 OOP,也就是说,Fortran 中的派生类型。
在 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
链接坏了,所以我把它贴在这里:

module m
!...
interface base
module procedure new_base
end interface

contains
!...
function new_base(I)
integer, intent(in) :: I
type(base) new_base

allocate(new_base%data(I))
new_base%data = I
end function
!...
end module
上面的接口(interface)为类型基定义了一个用户定义的构造函数。它的使用方式与结构构造函数类似。它甚至可以采用参数关键字。
然后我找到了一些其他的方法来做到这一点。
在这里,我列出了一些似乎可行的方法,但我只测试了第一种和第二种:
  • 与它们应该构造的派生类型同名的泛型接口(interface),请参见上面的链接;
  • 使用类型绑定(bind)过程(这甚至不是“传统”构造函数)
    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
  • 使用静态构造函数或结构构造函数 (http://www.lahey.com/docs/lfenthelp/NLMOvUsInvConst.htm)
    但似乎这不适用于一般 Fortran http://www.lahey.com/docs/lfenthelp/NLMGSWhatIs.htm

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

    最佳答案

    好的,所以我假设您在 How to override a structure constructor in fortran 上阅读了答案。我将回答您在评论中提出的问题。评论中没有足够的地方来回答这个问题。

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

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

    对于类型

    type t1
    integer :: i = 1
    integer, pointer :: ip => null()
    integer, allocatable :: ap
    end type

    您可以像调用默认构造函数一样
    instance = t1()

    这是完全合法的, i将为 1, ip将指向 nullap不会被分配。

    或者您可以将其称为
     instance = t1(ap=5)

    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

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

    至于嵌套类型,最好将构造函数作为函数来完成,无论它们是默认的还是用户定义的:
    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.)

    关于constructor - Fortran 派生类型实例的用户定义构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46570745/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com