首页 > 解决方案 > Fortran 派生类型继承

问题描述

假设我有一个派生类型,它作为变量bar_a包含在派生类型中。 现在我想扩展并创建一个名为. 我尝试了以下方法:foo_abar
bar_abar_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_ain一部分的类型绑定过程foo_b

标签: oopfortranderived-types

解决方案


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

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 行的定义)在第 11 行已经有一个变量bar,您尝试bar在第 21 行添加另一个变量。


推荐阅读