Interface Fortran派生类型
我想知道是否有可能在Fortran中定义一个派生类型,自动返回正确的类型,而不专门调用该类型,例如Interface Fortran派生类型,interface,fortran,derived-types,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
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
模块DervType
隐式无
类型,公共::mytype
雷亚尔(8)::r
整数::i
逻辑::l
端型
端模块DervType
程序测试类型
使用DervType
隐式无
类型(mytype)::测试
测试=1 找到了解决这个问题的方法,其实很简单。代码如下:
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
我现在尝试在程序中使用变量(例如,做一些算术计算等),但这似乎是相当困难的,如果不是不可能的话。我可以再问一个问题。是的,可以定义作业。你能试试看它是否符合你的要求吗?我想这与您的有关,但您可以在不使用多态性的情况下执行此操作。另请参见:。但这是您问题的一个非常具体的方面。也就是说,可以执行test=x
,以便test
集合的组件在某种程度上由x
的类型决定。然而,这就是你的意思吗?“自动返回正确类型”部分建议您可能需要执行一些更奇特的操作(如callsub(test)
如果参数为真,则其行为类似于callsub(test%r)
),等等)。谢谢您的回答!是的,我想这一切都是相关的,即使我放弃了其他东西。。。如果我编译上面的代码,我会得到:错误:无法将REAL(4)转换为TYPE(mytype)
,因此这不起作用。对不起,我看过你链接中的例子,但我不明白。我确实需要一个接口,对吗?所以我必须定义几个函数(real、int、logic)并通过接口分配它们?我要试试看!谢谢这是个坏主意。当有人引用test
时,您无法知道他们想要哪个值-实数、整数、逻辑或字符。所以你的赋值看起来和你的值访问不同,这让人困惑。好吧,我想这取决于你想如何使用它。目前我同意这种情况,但这不是问题的一部分。我只是想知道如何或者是否可以在不知道输入类型的情况下为延迟类型赋值。目前我正在研究另一种方法。实际上,在一个接口中包含许多过程的解决方案有一个优点,即如果您试图分配一个未包含的类型,您将得到一个编译时错误。Otoh,将类(*)与select类型一起使用时,最好是出现运行时错误(考虑使用select default子句)