首页 > 解决方案 > 是否可以将派生类型传递给fortran中的类子例程

问题描述

系统:

mac osx catalina (latest)
gfortran 9.2

在下面的文件中,我试图定义一个抽象基类,其中包含一个名为 print 的方法的接口。有问题的子例程接受两个参数, aparent1_abc和 the parent2_abc

在实现子类的方法时,我需要为两个参数传递派生类型的参数,而不仅仅是this方法。

我想知道我是否违反了该规则,或者如果没有,我该怎么做?最终我可以通过不在基类中定义方法而只在类层次结构的最底层定义它来克服这个问题,并不是说有那么多级别,但当然有理由在 abc 中定义方法.

这是文件:

module dt
  implicit none

  type, abstract :: parent1_abc
   contains
     procedure(parent2_abc_print), deferred, pass(this) :: print
  end type parent1_abc

  type, abstract :: parent2_abc
     character(len=256) :: id
  end type parent2_abc

  interface
     subroutine parent2_abc_print(this, obj)
       import
       class(parent1_abc) :: this
       class(parent2_abc) :: obj
     end subroutine parent2_abc_print
  end interface

  type, extends(parent1_abc) :: child1
   contains
     procedure, pass(this) :: print => child1_print
  end type child1


  type, extends(parent2_abc) :: child2
  end type child2

contains

  subroutine child1_print(this, obj)
    class(child1) :: this
    class(child2) :: obj
    print *, obj%id
  end subroutine child1_print

end module dt

编译gfortran derivedtype.f90 -c

并得到消息:

> gfortran derivedtype.f90 -c
derivedtype.f90:23:14:

   23 |      procedure, pass(this) :: print => child1_print
      |              1
Error: Argument mismatch for the overriding procedure 'print' at (1): Type mismatch in argument 'obj' (CLASS(__class_dt_Child2_t)/CLASS(__class_dt_Parent2_abc_t))
derivedtype.f90:21:38:

   21 |   type, extends(parent1_abc) :: child1
      |                                      1
Error: Derived-type 'child1' declared at (1) must be ABSTRACT because 'print' is DEFERRED and not overridden

标签: objectinheritancefortran

解决方案


推荐阅读