Fortran派生类型 [英] Fortran derived types
问题描述
我想知道是否有可能在Fortran中定义一个派生类型,该派生类型自动返回正确的类型,而无需专门调用该类型,例如var%real
?这是一个解释我的意思的示例:
I was wondering if it is somehow possible to define a derived type in Fortran which automatically returns the right type, without calling the type specifically e.g. var%real
? Here's an example to explain what I mean:
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
是否可以通过定义某种接口分配(使=重载)或类似的方式来实现?这有可能吗?
Would this be possible by defining some sort of interface assignment (overload the =) or something like that? Is this even possible?
谢谢!任何帮助表示赞赏!
Thanks! Any help appreciated!
推荐答案
找到了解决方案,它实际上非常简单.这是代码:
Found a solution to this and it was actually quite simple. Here's the code:
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
我现在正在尝试在程序中使用变量(例如进行一些算术运算等),但这似乎很困难,即使不是不可能.我可能会对此提出另一个问题.
I'm trying to use the variables within a program now (e.g. do some arithmetic calculations, etc.) but that seems to be rather difficult if not impossible. I might start another question about that.
这篇关于Fortran派生类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!