如何在Fortran模块中声明符合抽象接口的自定义子程序?
如何在Fortran模块中声明符合抽象接口的子程序
当然可以把符合抽象接口的自定义子程序整合到模块里,你之前的写法编译失败是因为误用了abstract interface块——这个块是用来定义新的抽象接口的,而不是用来关联已有抽象接口和具体子程序的。下面给你两种正确的实现方式:
方法一:直接声明子程序关联抽象接口
在模块的声明部分,直接用procedure(抽象接口名)来指定你的子程序符合该接口,然后在contains块里实现具体的子程序即可:
module custom_subs use abstract_module ! 导入已有的抽象接口模块 implicit none ! 声明custom子程序符合sub_interface抽象接口 procedure(sub_interface) :: custom contains ! 实现具体的custom子程序,参数列表必须和sub_interface完全匹配 subroutine custom(arg1, arg2) ! 这里的参数类型、intent等要严格和sub_interface一致 integer, intent(in) :: arg1 real, intent(out) :: arg2 ! 子程序逻辑 arg2 = real(arg1) * 2.0 end subroutine custom end module custom_subs
方法二:用普通interface块批量关联(适合多个子程序)
如果你有多个子程序都需要关联同一个抽象接口,可以用普通的interface块(注意不是abstract interface)来批量声明:
module custom_subs use abstract_module implicit none ! 批量声明多个子程序都符合sub_interface接口 interface procedure(sub_interface) :: custom, custom_double, custom_half end interface contains subroutine custom(arg1, arg2) integer, intent(in) :: arg1 real, intent(out) :: arg2 arg2 = real(arg1) * 2.0 end subroutine custom subroutine custom_double(arg1, arg2) integer, intent(in) :: arg1 real, intent(out) :: arg2 arg2 = real(arg1) * 4.0 end subroutine custom_double subroutine custom_half(arg1, arg2) integer, intent(in) :: arg1 real, intent(out) :: arg2 arg2 = real(arg1) * 0.5 end subroutine custom_half end module custom_subs
关键注意事项
- 具体子程序的**参数列表、类型、intent属性、返回值(如果是函数)**必须和抽象接口
sub_interface完全一致,否则编译器会抛出类型不匹配的错误。 - 在主程序中使用时,只需要导入
custom_subs模块,就可以直接调用这些符合接口的子程序,不需要再重复声明:
program testsub use abstract_module use custom_subs implicit none ! 直接调用test_call,传入模块里的custom子程序 call test_call(custom) ! 也可以调用其他关联好的子程序 call test_call(custom_double) end program testsub
总结一下:完全不需要把这些子程序留在主程序中,只要正确关联抽象接口和具体实现,就能把它们优雅地整合到模块里,方便复用和维护。
内容的提问来源于stack exchange,提问作者senseiwa
相关产品推荐
相关产品推荐

