Modern Fortran: Calling an ancestor procedure from descendent

后端 未结 1 1464
广开言路
广开言路 2021-01-20 12:40

I am starting to use the OO features of Modern Fortran and am already familiar with OO in other languages. In Delphi (Object Pascal) it is common to call an ancestor version

相关标签:
1条回答
  • 2021-01-20 13:26

    Here is some sample code that tries to implement the comment by @HighPerformanceMark (i.e., a child type has a hidden component that refers to the parent type).

    module testmod
        implicit none
    
        type tClass
            integer :: i = 123
        contains
            procedure :: Clear => Clear_Class
        endtype
    
        type, extends(tClass) :: tSubClass
            integer :: j = 456
        contains
            procedure :: Clear => Clear_SubClass
        endtype
    
    contains
    
        subroutine Clear_Class( this )
            class(tClass) :: this
            this % i = 0
        end
    
        subroutine Clear_SubClass( this )
            class(tSubClass) :: this
            this % j = 0
            call this % tClass % Clear()  !! (*) calling a method of the parent type
        end
    end
    
    program main
        use testmod
        implicit none
        type(tClass) :: foo
        type(tSubClass) :: subfoo
    
        print *, "foo (before) = ", foo
        call foo % Clear()
        print *, "foo (after)  = ", foo
    
        print *, "subfoo (before) = ", subfoo
        call subfoo % Clear()
        print *, "subfoo (after)  = ", subfoo
    end
    

    which gives (with gfortran-8.2)

     foo (before) =          123
     foo (after)  =            0
     subfoo (before) =          123         456
     subfoo (after)  =            0           0
    

    If we comment out the line marked by (*), subfoo % i is kept unmodified:

     foo (before) =          123
     foo (after)  =            0
     subfoo (before) =          123         456
     subfoo (after)  =          123           0
    
    0 讨论(0)
提交回复
热议问题