Fortran 派生类型继承

时间:2021-02-01 18:06:40

标签: oop fortran derived-types

假设我有一个派生类型 bar_a,它作为变量 foo_a 包含在派生类型 bar 中。
现在我想扩展 bar_a 并创建一个名为 bar_b 的新派生类型。我尝试了以下方法:

program main
  implicit none

  ! Base types -----------
  
  type :: bar_a
    integer :: a
  end type bar_a
  
  type :: foo_a
    type(bar_a) :: bar
  end type foo_a
  
  ! Extended types -------
  
  type, extends(bar_a) :: bar_b
    integer :: b
  end type bar_b
  
  type, extends(foo_a) :: foo_b
    type(bar_b) :: bar ! <-- Component ‘bar’ at (1) already in the parent type
  end type foo_b
  
  ! ----------------------

  type(foo_b) :: foo

  print *, foo%bar%a
  print *, foo%bar%b

end program main

但我收到一个编译器错误:“(1) 处的组件‘bar’已经在父类型中了”。

有没有办法扩展 foo_a 以使其包含我尝试过的新派生类型 bar_b,或者有什么方法可以“覆盖”bar 变量声明?我想继承将成为 foo_afoo_b 一部分的类型绑定过程。

1 个答案:

答案 0 :(得分:1)

当我尝试编译时,我得到了一个更好的信息:

aa.f90:21:22:

   10 |   type :: foo_a
      |               2
......
   21 |     type(bar_b) :: bar ! <-- Component ‘bar’ already in the parent type
      |                      1
Error: Component ‘bar’ at (1) already in the parent type at (2)

这似乎合乎逻辑,您尝试使用名称为 foo_a 的元素扩展 bar,但是您扩展的类型(根据第 10 行的定义)已经有一个变量 {{1} } 在第 11 行,您尝试在第 21 行添加另一个 bar