代码之家  ›  专栏  ›  技术社区  ›  bob.sacamento

Fortran模块是否可以覆盖另一个模块中的子例程?

  •  0
  • bob.sacamento  · 技术社区  · 3 年前

    (顺便说一句,这不涉及派生类型中的函数。)

    我想做如下的事情。我有 module test1 :

    cat测试_mod_1.F90

    module test1
    
            contains
    
                    subroutine sub1()
                           ! do interesting stuff that any inheriting module
                           ! will want to do ....
                           ! then do something specific to this module:
                            call sub2()
                    end subroutine sub1
    
                    subroutine sub2()
                            print *, "I am test1"
                    end subroutine sub2
    
    end module test1
    

    test1 由使用 module test2 :

    > cat test_mod_2.F90
    module test2
    
    
            use test1, test1_sub2 => sub2
    
            contains
    
                    subroutine sub2()
                            print *,"I am test2"
                    end subroutine sub2
    
    end module test2
    

    (顺便说一句,如果没有“=>”行, test2 甚至不会编译。)

    然后我有一个使用 测试2 测试1 :

    > cat testmain.F90
    program testmain
            use test2
            call sub1()
    end program
    

    我想得到消息“我正在测试2”,但事情没有解决:

    > gfortran -o tester test_mod_1.F90 test_mod_2.F90 testmain.F90
    > ./tester
     I am test1
    

    有什么方法可以说服主程序使用 测试2 sub2() 而不是 测试1 是吗?

    1 回复  |  直到 3 年前
        1
  •  2
  •   IanH    3 年前

    如果您希望sub1中的可定制行为最好由用户提供的过程来描述,那么将用户提供的程序作为参数传递。

    module test1
      implicit none
    contains
      subroutine sub1(sub2_override)
        ! Declare sub2_override to be a optional dummy procedure that 
        ! has the same interface as the procedure known as sub2.  
        !
        ! Actual procedures associated with this dummy must having matching 
        ! characteristics.
        procedure(sub2), optional :: sub2_override
        
        !...
        if (present(sub2_override)) then
          call sub2_override
        else
          call sub2
        end if
      end subroutine sub1
      
      subroutine sub2
        print *, "I am test1"
      end subroutine sub2
    end module test1
    
    program testmain
      use test1
      implicit none
      call sub1
      call sub1(my_sub2)
    contains
      subroutine my_sub2
        print *, "I am my_sub2"
      end subroutine my_sub2
    end program testmain
    
    推荐文章