Fortran派生类型

时间:2018-09-26 10:29:59

标签: interface fortran derived-types

我想知道是否有可能在Fortran中定义一个派生类型,该派生类型自动返回正确的类型,而无需专门调用该类型,例如var%real?这是一个解释我的意思的示例:

module DervType

  implicit none

  type, public :: mytype
    real(8) :: r
    integer :: i
    logical :: l
  end type

end module DervType

program TestType

  use DervType

  implicit none

  type(mytype) :: test

  test = 1.                   !! <-- I don't want to use test%r here

end program TestType

是否可以通过定义某种接口分配(使=重载)或类似的方式来实现?这有可能吗?

谢谢!任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:2)

找到了解决方案,实际上很简单。这是代码:

module DervType

  implicit none

  type, public :: mytype
    real(8)                       :: r
    integer                       :: i
    character(len=:), allocatable :: c
    logical :: l
  end type

  interface assignment(=)                 // overload = 
    module procedure equal_func_class
  end interface

contains

  subroutine equal_func_class(a,b)

    implicit none

    type(mytype), intent(out) :: a
    class(*), intent(in)      :: b

    select type (b)
        type is (real)
            print *, "is real"
            a%r = b
        type is (integer)
            print *, "is int"
            a%i = b
        type is (character(len=*))
            print *, "is char"
            a%c = b
        type is (logical)
            print *, "is logical"
            a%l = b 
    end select

    return

  end subroutine equal_func_class  

end module DervType

program TestType

  use DervType

  implicit none

  type(mytype) :: test

  test = 1.      // assign real 
  test = 1       // assign integer
  test = "Hey"   // assign character
  test = .true.  // assign logical

  print *, "Value (real)      : ", test%r
  print *, "Value (integer)   : ", test%i
  print *, "Value (character) : ", test%c
  print *, "Value (logical)   : ", test%l

end program TestType

我现在正在尝试在程序中使用变量(例如进行一些算术运算等),但这似乎很困难,即使不是不可能。我可能会对此提出另一个问题。