如何覆盖fortran中的结构构造函数 [英] How to override a structure constructor in fortran
问题描述
目前是否可以覆盖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中的结构构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!