Fortran派生类型

弗洛里安·拉戈斯尼格(Florian Ragossnig)

我想知道是否有可能在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

通过定义某种接口分配(重载=)或类似的方法,是否可能?这有可能吗?

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

弗洛里安·拉戈斯尼格(Florian Ragossnig)

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Fortran派生类型分配

以Fortran派生类型“扩展”功能

FORTRAN动态分配派生类型

在fortran中分配嵌套派生类型

在单独的文件中构造Fortran派生类型

指向派生类型子例程的Fortran过程指针

Fortran通过过程调用选择派生类型

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

不复制Fortran派生类型的指针成员

使用没有 % 的 fortran 派生类型变量

包含可从C访问的指针的Fortran派生类型

派生类型的组件中的 Fortran 不匹配

如何以Fortran派生类型存储对过程的引用

Fortran派生类型的“初始”语句/自动构造函数

逐步派生类型

SignalR派生类型

指针访问类型后,派生类型中的fortran字符串的奇怪行为

Fortran 2003,将派生类型传递给父类型参数

通过C函数定义的Fortran派生类型构造函数(II)

计算 Fortran90 中派生类型中定义的字符串的特定字母

了解Fortran如何初始化模块中定义的派生类型的数组

将派生类型作为参数的函数作为 Fortran 中的参数传递

指向数组的数组,作为Fortran派生类型中的成员变量

Fortran 派生类型可以包含来自不同模块的组件吗?

OOP Fortran,模块中定义的派生类型和对象:有什么缺点吗?

在现代Fortran中的模块内使用子例程加载派生类型

在Fortran派生类型中持有指向C函数的指针

Python ctypes在结构字段中将指针传递给Fortran派生类型

如何在Fortran中支持“相同”派生类型的多个版本?