如何将子程序作为输入传递给派生数据类型的字段?
我有一个链接列表,我想循环播放,我只想在特定字段上工作,但我希望将字段“name”作为输入,以便我可以在不同的字段上调用相同的函数清单。
例如:
program main
implicit none
! ----- variables declaration
type :: element
real :: u1
real :: u2
type (element), pointer :: next => null()
end type element
type (element), pointer :: first, last, iele
! ----- code
allocate( first )
last => first
first %u1 = 0
first %u2 = 0
allocate( first %next )
last => first %next
last %u1 = 10
last %u2 = 20
call addten( u1, first )
call addten( u2, first )
iele => first
do while ( associated( iele ) )
write(*,*) iele %u1
iele => iele %next
end do
end program main
! =====
subroutine addten( u, first )
implicit none
! ----- variables declaration
type :: element
real :: u1
real :: u2
type (element), pointer :: next => null()
end type element
real, pointer :: u
type (element), pointer :: iele
! ----- code
iele => first
do while ( associated( iele ) )
iele %u = iele %u + 10
iele => iele %next
end do
end subroutine addten
答案 0 :(得分:1)
根据Fortran标准,如果您在两个地方定义类型,则不是同一类型,尽管它具有相同的名称和定义。您必须使用contains
或更好的place it in a module来定义内部程序。
在你的情况下,你想要浏览链表,你想首先传递整个变量,但mabe作为指针:
type(element), pointer, intent(in) :: first
之后你必须知道你在soubrutine中改变了哪个组件。无法直接传递此信息,您需要传递子程序理解为开关的辅助变量:
integer, intent(in) :: comp
select case (comp)
case (1)
!add to component u1
case (2)
!add to component u2
end select
所以看起来像(未经测试):
module list
implicit none
type :: element
real :: u1
real :: u2
type (element), pointer :: next => null()
end type element
!here any other subroutines directly connected to the list object
end module list
module other_list_procedures
use list
implicit none
subroutine addten( comp, first )
type (element), pointer, intent(in) :: first
integer, intent(in) :: comp
type (element), pointer :: iele
iele => first
do while ( associated( iele ) )
select case (comp)
case (1)
iele%u1 = iele%u1 + 10
case (2)
iele%u2 = iele%u2 + 10
end select
iele => iele%next
end do
end subroutine addten
end module