我试图隐藏真实数据类型和复杂数据类型之间的区别。在 FORTRAN 2003 中,我认为可能有办法做到这一点。
目标是定义一个多态可分配数组,其类型可以在运行时决定。另外,还有一个子程序可以用多态数组来做一些代数(同样的方程适用于真实和复杂的数据)。
为了做到这一点,我做了两次尝试:
方法一:
module poly
implicit none
private
type, abstract, public :: MyType
contains
procedure, public :: Constructor
endtype MyType
type, extends(MyType), public :: MyTypeR
real(8), allocatable :: AllData(:)
endtype MyTypeR
type, extends(MyType), public :: MyTypeI
complex(8), allocatable :: AllData(:)
endtype MyTypeI
contains
subroutine Constructor(this, Nsize)
class(MyType), intent(inout) :: this
integer, intent(in) :: Nsize
select type(this)
type is(MyTypeR)
allocate(this%AllData(Nsize))
type is(MyTypeI)
allocate(this%AllData(Nsize))
endselect
endsubroutine
endmodule poly
! Algebra subroutine
module Operation
contains
subroutine Square(Array)
class(*), intent(inout) :: Array(:)
select type(Array)
class is(real(8))
Array = Array**2
class is(complex(8))
Array = Array**2
endselect
endsubroutine Square
endmodule Operation
! Main
program test
use poly
use Operation
class(MyType), allocatable :: t1, t2
integer :: i
logical :: IfComplex = .true.
if(IfComplex) then
allocate(MyTypeI::t1)
else
allocate(MyTypeR::t1)
endif
call t1%Constructor(4)
call Square(t1%AllData)
endprogram test
方法 B(无限多态可分配变量):
module poly
implicit none
private
type, public :: MyType
class(*), allocatable :: AllData(:)
contains
procedure, public :: Constructor
endtype MyType
contains
subroutine Constructor(this, Nsize, IfComplex)
class(MyType), intent(inout) :: this
integer, intent(in) :: Nsize
logical, intent(in) :: IfComplex
if(IfComplex) then
allocate(complex(8)::this%AllData(Nsize))
else
allocate(real(8)::this%AllData(Nsize))
endif
endsubroutine
endmodule poly
! Same algebra subroutine
! Main
program test
use poly
use Operation
type(MyType) :: t1, t2
integer :: i
call t1%Constructor(4, .true.)
call Square(t1%AllData)
endprogram test
然后我在这两种方法中的代数子例程都有问题:在内在赋值语句中,变量不应是多态的。任何建议将不胜感激。