【问题标题】:How to use interface block for type overloading如何使用接口块进行类型重载
【发布时间】:2017-03-09 20:10:25
【问题描述】:

我编写了一个 Fortran 代码来读取不同的文本文件。每个文本文件都有自己的类型,它定义了从定义一般操作的抽象类型继承的读取过程:

module FileImporter_class
implicit none
private
type, abstract, public :: FileImporter
.
.
contains
    procedure, public :: ProcessFile
.
.
end type FileImporter
contains
.
.
subroutine ProcessFile(self,FileName)
implicit none
    ! Declaring Part
    class(FileImporter) :: self
    character(len=*) :: FileName

    ! Executing Part
    call self%SetFileName(FileName)
    call self%LoadFileInMemory
    call self%ParseFile
end subroutine ProcessFile
end module FileImporter_class

继承类如下:

module optParser_class
use FileImporter_class
implicit none
type, public, extends(FileImporter) :: optParser
.
. 
contains
    procedure, public :: ParseFile
end type optParser
interface optParser
    procedure ProcessFile
end interface
contains
.
.
end module optParser_class

我的问题是关于接口块的。我想通过简单地调用类型来调用过程ProcessFile,所以call optParser('inputfile.txt')。显示的这个变体给出了编译错误(ProcessFile 不是函数也不是子例程)。我可以通过在optParser_class 模块中放置一个ProcessFile 函数来解决这个问题,但是我必须对每个继承类都这样做,我自然想避免这种情况。有什么建议吗?

【问题讨论】:

    标签: inheritance interface fortran overloading fortran2003


    【解决方案1】:

    Fortran 标准不允许将子例程放入重载类型名称的接口块中。

    只有函数可以放入此类接口,然后它们通常用于返回该类型的对象(构造函数或初始化程序)。

    相反,您应该将其称为类型绑定过程,因为 optParserFileImporter 继承自

     call variable_of_optParser_type%ProcessFile('inputfile.txt')
    

    在 Fortran 中没有可以在没有实例的情况下调用的类 Python 类方法。注意 ProcessFileself 参数,所以它必须接收一些对象实例。

    顺便说一句,我建议您制定一个约定,无论您的类型是以小写字母还是大写字母开头,并坚持使用它以避免混淆。

    【讨论】:

    • 非常感谢。我还是 Fortran 中的 OOP 的新手,所以我不知道什么是适用和/或允许的,什么不是。
    猜你喜欢
    • 2020-06-07
    • 2021-05-13
    • 2015-10-31
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    相关资源
    最近更新 更多