现代Fortran:从后代调用祖先过程

时间:2019-03-29 10:34:40

标签: fortran

我开始使用Modern Fortran的OO功能,并且已经熟悉其他语言的OO。在Delphi(对象Pascal)中,通常在其覆盖的后代过程中调用过程的祖先版本,甚至有“继承”的语言声明也允许这样做。我找不到等效的Fortran构造-但可能正在寻找错误的东西。请参阅下面的简单示例。任何建议,不胜感激。

type tClass
  integer :: i
contains
  procedure Clear => Clear_Class
end type tClass

type tSubClass
  integer :: j
contains
  procedure Clear => Clear_SubClass
end type tSubClass

subroutine Clear_Class
  i = 0
end subroutine

subroutine Clear_SubClass
  inherited Clear ! this is the Delphi way
  j = 0
end subroutine

1 个答案:

答案 0 :(得分:2)

这是一些示例代码,试图通过@HighPerformanceMark实现注释(即,子类型具有引用父类型的隐藏组件)。

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

提供了(使用gfortran-8.2)

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

如果我们注释掉以(*)标记的行,则subfoo % i将保持不变:

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