【发布时间】:2018-05-16 11:29:11
【问题描述】:
我尝试创建一个无需使用通用过程即可接受不同输入类型的过程。实际上,(在这种情况下)我更喜欢手动设置过程指针的目标来定义要使用的过程,而不是通用过程。
这就是我对以下几乎最小的示例所做的。
module mo
implicit none
type :: TypeB
character(len=5) :: info='Hello'
contains
procedure, pass(fd) :: say_hello
end type TypeB
type :: TypeA
character(len=4) :: txt='Hola'
!type(TypeB) :: Tb
end type TypeA
type, extends(TypeA) :: TypeC
character(len=4) :: tt='Hey!'
type(TypeB) :: Tb
end type TypeC
type, extends(TypeA) :: TypeD
character(len=3) :: tt='Ho!'
character(len=3) :: ti='you'
!type(TypeB) :: Tb
end type TypeD
type(TypeC) :: Tc
type(TypeD) :: Td
procedure(), pointer :: proc
class(TypeA), allocatable :: CA
contains
subroutine say_hello(fd)
implicit none
! type(TypeB), intent(inout) :: fd
class(TypeB), intent(inout) :: fd
print *, fd%info
end subroutine say_hello
subroutine procC(fd, args)
implicit none
! class(TypeC), intent(inout) :: fd
type(TypeC), intent(inout) :: fd
real :: args
print*, args
print*, fd%tt
call fd%Tb%say_hello()
end subroutine procC
subroutine procD(fd, args)
implicit none
! class(TypeD), intent(inout) :: fd
type(TypeD), intent(inout) :: fd
! class(TypeA), intent(inout) :: fd
real :: args
print*, args
print*, fd%tt
print*, fd%ti
end subroutine procD
end module mo
program p
use mo
implicit none
print* , 'START'
print *, Tc%tb%info
print *, Tc%txt
call Tc%Tb%say_hello()
call procC(Tc, 1.0)
call procD(Td, 2.0)
print*, 'OK'
allocate(TypeD :: CA)
proc =>procD
call proc(CA, 3.0)
deallocate(CA)
allocate(TypeC :: CA)
proc =>procC
call proc(CA, 4.0)
deallocate(CA)
print*, 'END'
end program p
当我在 Linux 上使用 ifort 编译时,我得到了预期的结果,但是当我在 Windows 或 Linux(gfortran 5.5.0 和 6.4.0)上使用 gfortran (MinGW 6.2.0) 编译时,我得到了一些奇怪的结果:
START
Hello
Hola
Hello
1.00000000
Hey!
Hello
2.00000000
Ho!
you
OK
3.00000000
@R
4.00000000
ÇR@
END
当我在我的大程序中使用这种方法时,情况变得更糟了。
那么,有没有办法避免这些问题呢?这是gfortran的错误吗?还是我误会了什么?
【问题讨论】: