子例程的名称可以是Fortran中的变量吗? [英] The name of a subroutine can be a variable in Fortran?
本文介绍了子例程的名称可以是Fortran中的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道Fortran中是否有类似的东西.当然,此示例不会编译,但我认为您可以理解.
I was wondering if there is something similar to this in Fortran. Of course this example does not compile but I think you can get the idea.
program test
character(1):: sub
sub='A'
call sub
sub='B'
call sub
end program
subroutine A
print*,'OK! A'
end subroutine A
subroutine B
print*,'OK! B'
end subroutine B
推荐答案
您无法通过设置字符变量来完成此操作,但是可以使用过程指针来完成此操作.我已经稍微修改了您的示例以实现这一点.参见:
You cannot accomplish this by setting a character variable, but you can do this with procedure pointers. I've modified your example slightly to implement that. See:
program test
implicit none
abstract interface
subroutine no_args
end subroutine
end interface
procedure(no_args), pointer :: sub => null()
sub => A
call sub
sub => B
call sub
contains
subroutine A
implicit none
print *,"OK! A"
end subroutine
subroutine B
implicit none
print *,"OK! B"
end subroutine
end program
更改为:
- 定义过程指针的接口
- 将
sub
声明为指向该抽象接口的过程指针
- Define an interface for the procedure pointer
- Declare
sub
as a procedure pointer to that abstract interface
然后,您可以将sub
分配给不带参数的子例程(因为这就是接口所说明的内容),然后按照您的设想通过sub
对其进行调用.
You can then assign sub
to subroutines that take no arguments (since that is the what the interface says) and call them through sub
the way you envision.
这篇关于子例程的名称可以是Fortran中的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文