【发布时间】:2018-10-09 14:43:55
【问题描述】:
对不起,又是我!
尽管我在 Fortran 中的 OOP 越来越好(这可能是我用过的最疯狂的事情),但我在继承方面遇到了困难。不幸的是,我不明白允许我这样做的语法。
基本上,我想要做的是覆盖赋值运算符=,它允许我返回任何原始类型。只有一种基本类型 (real) 的基本示例如下所示:
module overload
implicit none
public func, assignment(=)
interface assignment(=)
module procedure equalAssignmentReal
!! additional procedures for integer, character, logical if neccessary
end interface
contains
subroutine equalAssignmentReal(lhs, rhs) !! <-- all these subroutines should be in the parent class
implicit none
real, intent(out) :: lhs
class(*), intent(in) :: rhs
select type(rhs)
type is (real)
lhs = rhs
end select
return
end subroutine equalAssignmentReal
function func(string) result(res) !! <-- I want this function in the child class
implicit none
character(len=*), intent(in) :: string
class(*), allocatable :: res
if ( string == "real" ) allocate(res, source=1.0)
return
end function func
end module overload
program test
use overload
implicit none
real :: var
var = func('real')
print *, "var = ", var
end program test
这在使用 GNU Fortran 编译时有效(不适用于 Intel,因为它们允许内部赋值重载)。所以我现在的问题是如何在包含所有赋值重载(实数、整数、字符、逻辑)的单独模块中定义 父类 并在 子类 仅包含func?在程序中,我只想包含子类并使用以下内容分配值:
type(child_class) :: child
real :: var
var = child%func('real')
任何帮助表示赞赏!
【问题讨论】:
-
我不明白父子类型在这个排列中的作用是什么。类型绑定赋值必须涉及绑定类型,在赋值的左侧或右侧。在您的最后一个示例块中,左侧是实数类型,右侧是无限多态(~无类型)。
-
你使用了“覆盖”这个词。您指的是“过载”吗?
标签: oop fortran assignment-operator