【问题标题】:Fortran derived type inheritanceFortran 派生类型继承
【发布时间】:2021-02-01 18:06:40
【问题描述】:

假设我有一个派生类型 bar_a,它作为变量 bar 包含在派生类型 foo_a 中。
现在我想扩展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_b 中继承将成为foo_a 一部分的类型绑定过程。

【问题讨论】:

    标签: oop fortran derived-types


    【解决方案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)
    

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

    【讨论】:

    • 有没有办法“覆盖”声明?就我而言,我想将属于foo_a 的类型绑定过程“转移”到foo_b
    • 这是一个不同的问题,您应该在问题中明确说明(编辑当前问题或提出新问题),我的回答是基于所提出的问题。
    • 对不起。我尴尬地提出了这个问题。我将问题编辑得更清楚。
    猜你喜欢
    • 1970-01-01
    • 2012-10-23
    • 2019-03-02
    • 1970-01-01
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    相关资源
    最近更新 更多