问题描述
目前是否可以覆盖 Fortran 中的结构构造函数?我见过这样的提议示例(例如在 Fortran 2003 规范中):
Is it currently possible to override the structure constructor in Fortran? I have seen proposed examples like this (such as in the Fortran 2003 spec):
module mymod
type mytype
integer :: x
! Other stuff
end type
interface mytype
module procedure init_mytype
end interface
contains
type(mytype) function init_mytype(i)
integer, intent(in) :: i
if(i > 0) then
init_mytype%x = 1
else
init_mytype%x = 2
end if
end function
end
program test
use mymod
type(mytype) :: x
x = mytype(0)
end program
由于冗余变量名称,这基本上会产生一堆错误(例如,错误:'mytype' 的 DERIVED 属性与 (1) 处的 PROCEDURE 属性冲突).Fortran 2003 示例的逐字副本会生成类似的错误.我已经在 gfortran 4.4、ifort 10.1 和 11.1 中尝试过,它们都产生了相同的错误.
This basically generates a heap of errors due to redundant variable names (e.g. Error: DERIVED attribute of 'mytype' conflicts with PROCEDURE attribute at (1)). A verbatim copy of the fortran 2003 example generates similar errors. I've tried this in gfortran 4.4, ifort 10.1 and 11.1 and they all produce the same errors.
我的问题:这只是 fortran 2003 的一个未实现的功能吗?还是我错误地实施了这个?
My question: is this just an unimplemented feature of fortran 2003? Or am I implementing this incorrectly?
我遇到了错误报告和针对此问题发布了 gfortran 补丁.但是,我尝试使用 11 月构建的 gcc46,但没有运气和类似错误.
I've come across a bug report and an announced patch to gfortran regarding this issue. However, I've tried using a November build of gcc46 with no luck and similar errors.
编辑 2:上面的代码似乎可以使用 Intel Fortran 12.1.0.
Edit 2: The above code appears to work using Intel Fortran 12.1.0.
推荐答案
我查阅了我的 Fortran 2008 标准副本.这确实允许您定义一个与派生类型同名的通用接口.我的编译器(Intel Fortran 11.1)不会编译代码,所以我怀疑(手头没有 2003 标准的副本)这是 Fortran 2003 标准的一个尚未实现的功能.
I consulted my copy of the Fortran 2008 standard. That does allow you to define a generic interface with the same name as a derived type. My compiler (Intel Fortran 11.1) won't compile the code though so I'm left suspecting (without a copy of the 2003 standard to hand) that this is an as-yet-unimplemented feature of the Fortran 2003 standard.
除此之外,您的程序中存在错误.您的函数声明:
Besides that, there is an error in your program. Your function declaration:
type(mytype) function init_mytype
integer, intent(in) :: i
指定函数规范中不存在的参数的存在和意图,它或许应该重写为:
specifies the existence and intent of an argument which is not present in the function specification, which should perhaps be rewritten as:
type(mytype) function init_mytype(i)
这篇关于如何在fortran中覆盖结构构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!