【问题标题】:Modern Fortran: Calling an ancestor procedure from descendent现代 Fortran:从后代调用祖先过程
【发布时间】:2019-03-29 19:33:18
【问题描述】:

我开始使用 Modern Fortran 的 OO 功能,并且已经熟悉其他语言的 OO。在 Delphi (Object 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

【问题讨论】:

  • 在 Fortran 派生类型功能的许多“文献”中并不明显,但是,在您的示例中,SubClass 有一个名为 Class 的组件,您可以调用绑定到该组件的过程,所以类似于call SubClass%Class%Clear(args) (当然,用类型实例的名称替换类型名称)。例如,请参阅gist.github.com/n-s-k/522f2669979ed6d0582b8e80cf6c95fd,甚至可能还有其他 Q 和 As here on SO。
  • @HighPerformanceMark 4.5.7.2#2 of ISO 1539-1:2010 “扩展类型具有标量、非指针、不可分配的父组件,其类型和类型参数与父类型相同。此组件的名称是父类型名称。”
  • @Jean-ClaudeArbaut:是的,我知道。但我不能像你一样逐字引用标准!
  • 谢谢马克 - 这将完美地完成这项工作。奇怪的是它在文献中没有得到更多的强调。我会(根据我的 Delphi 经验)认为这是一种非常常见的用法。

标签: fortran


【解决方案1】:

这里是一些示例代码,它试图通过@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

【讨论】:

  • 谢谢。正是我所需要的——很抱歉错过了“this”参数的明确声明。在我的辩护中,我习惯了 Delphi,其中“self”参数是隐藏/隐式的,并且始终在方法中可用。
猜你喜欢
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
相关资源
最近更新 更多