gpt4 book ai didi

fortran - 现代 Fortran : Calling an ancestor procedure from descendent

转载 作者:行者123 更新时间:2023-12-01 13:15:37 25 4
gpt4 key购买 nike

我开始使用现代 Fortran 的面向对象功能,并且已经熟悉其他语言的面向对象。在 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

最佳答案

下面是一些示例代码,尝试通过@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

关于fortran - 现代 Fortran : Calling an ancestor procedure from descendent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55415511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com