在接口块中"在定义之前使用派生类型"

Oba*_*bay 3 cygwin fortran types gfortran operator-keyword

在Windows上使用cygwin64,该程序将无法编译:

program test
  implicit none

  !define my type
  type myType
    real::foo
    integer::bar
  end type myType

  !define an operator for this type
  interface operator (>)
      logical function compare(a,b)
        type(myType),intent(in) :: a,b
        compare = a%foo>b%foo
      end function compare
  end interface operator (>)

  !simple example of operator usage
  type(myType) :: tfoo, tbar
  tfoo = card(1.,2); tbar = card(3.,4)
  print*, tfoo>tbar
end program test
Run Code Online (Sandbox Code Playgroud)

gfortran (只有参数是"std = f2008")告诉我:

type(myType),intent(in) :: a,b
                    1
Error: Derived type ‘mytype’ at (1) is being used before it is defined
Run Code Online (Sandbox Code Playgroud)

这对我来说很困惑,因为类型是在操作员之前定义的.我对Fortran比较新,所以这个示例代码可能会有更多错误.

这里发生同样的问题,但封装myType在一个单独的模块中并没有解决问题.

Ale*_*ogt 7

您的代码有几个问题,但是这个特殊错误是因为myType在主机范围内,而不是在接口块中.解决方案是将派生类型放在链接线程中建议的单独模块中,或者import从主机作用域单元中派生类型:

  interface operator (>)
      logical function compare(a,b)
        import myType
        type(myType),intent(in) :: a,b
      end function compare
  end interface operator (>)
Run Code Online (Sandbox Code Playgroud)

这在Fortran 2008 Standard,Cl.中有所描述.12.4.3.3"IMPORT声明":

1 IMPORT语句指定主机作用域单元中的命名实体可通过主机关联在接口主体中访问.以这种方式导入并在主机作用域单元中定义的实体应在接口主体之前显式声明.


接口块可能没有包含可执行语句 - 因此您在那里的分配无效.此外,card您的代码中未定义.