【发布时间】:2014-04-10 11:55:38
【问题描述】:
有没有办法使用与类型绑定过程相同的函数来处理两种或多种类型?例如。想象以下情况:
module definitions
implicit none
type type1
integer i
contains
procedure,pass :: init1
end type
type type2
integer i
contains
procedure,pass :: init2
end type
contains
subroutine init1(x)
class(type1),intent(inout) :: x
x%i=3
end subroutine
subroutine init2(x)
class(type2),intent(inout) :: x
x%i=3
end subroutine
end module
program test
use definitions
type(type1) ::a
type(type2) ::b
print*, a%i
print*, b%i
call a%init1
print*, a%i
print*, b%i
call b%init2
print*, a%i
print*, b%i
end program
如您所见,我使用了相同的子例程,但我觉得不得不定义它两次。所以我要求类似的东西
class(type1 .or. type2), intent(inout) :: x
或类似的。我已经尝试过 class(*) 但这当然不起作用,因为编译器不知道如何处理可能未定义的 x%i,即使不与选择类型块结合使用。我想提一下,真正的程序更复杂,因此将类型定义的相似部分合并然后扩展以定义这两种类型并不容易。 提前致谢!
【问题讨论】:
标签: fortran derived-class