子例程的名称可以是Fortran中的变量吗? [重复]

问题描述 投票:0回答:2

我想知道Fortran中是否有类似的东西。当然,此示例不会编译,但我认为您可以理解。

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
fortran fortran90 subroutine
2个回答
2
投票

您无法通过设置字符变量来完成此操作,但是可以使用过程指针来完成此操作。我已经稍微修改了您的示例以实现这一点。参见:

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声明为该抽象接口的过程指针

然后您可以将sub分配给不带参数的子例程(因为这是接口所说的,然后按照您的设想通过sub进行调用。


0
投票

您可以获得的最接近的是函数/过程指针,但这将是fortran-2003。通常,在给定输入“ A”或“ B”的情况下,将指针设置为指向subroutine Asubroutine BHow to alias a function name in Fortran上的更多详细信息>

© www.soinside.com 2019 - 2024. All rights reserved.