如何传递封装类型绑定函数?我玩了现代Fortran解释书(Metcalf,Reid和Cohen)中的例子,这就是我所做的:
module mod_polynoms_abstract
use mod_geometrics
implicit none
type, abstract :: bound_user_polynom
! No data
contains
procedure(user_polynom_interface), deferred :: eval
end type bound_user_polynom
abstract interface
real function user_polynom_interface(poly, pt)
import :: bound_user_polynom, point
class(bound_user_polynom) :: poly
type(point), intent(in) :: pt
end function user_polynom_interface
end interface
contains
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!Integral driver/chooser function
real function integral(userfun, options,status)
class(bound_user_polynom) :: userfun
integer, intent(in) :: options
real, intent(out) :: status
select case( options )
case (1)
integral = first_integral(userfun)
case (2)
integral = second_integral(userfun)
case default
integral = def_integral(userfun)
end select
end function
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!1. integration
real function first_integral(userfun)
class(bound_user_polynom),intent(in) :: userfun
first_integral= 1.0 * userfun%eval(point(x=2.,y=2.,z=0.))
end function
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!2. integration
real function second_integral(userfun)
class(bound_user_polynom),intent(in) :: userfun
second_integral= 2.0 * userfun%eval(point(x=2.,y=2.,z=0.))
end function
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!default integration
real function def_integral(userfun)
class(bound_user_polynom) :: userfun
def_integral= 0.0 * userfun%eval(point(x=2.,y=2.,z=0.))
end function
end module
这个编译,但是当我运行程序时,我会得到不同的结果。 当我调用该函数时,可能是这样的:
integral_result = integral(poly, 2 , status)
我有时得到正确的结果,用second_integral(userfun)计算
功能。但有时结果是错误的。
该函数无法正确计算userfun%eval(point(x=2.,y=2.,z=0.))
,但我不知道为什么。
这是正确的方法吗?
编辑:
我用:
COLLECT_GCC = gfortran4.8
COLLECT_LTO_WRAPPER =的/ usr /本地/的libexec / GCC / x86_64的未知-Linux的GNU / 4.8.0 / LTO-包装
Ziel:x86_64-unknown-linux-gnu
Konfiguriert mit:./ configure --disable-multilib
Thread-Modell:posix
gcc-Version 4.8.0(GCC)
userfun%eval(point(x = 2.,y = 2.,z = 0。))的正确结果是0.962435484 所以积分(poly,2,status)必须给我1.92487097。 但是当我执行该程序几次时,我得到了:
首次运行:1.92487097
第二轮:54877984.0
......:1.92487097
......:2.55142141E + 27
......:4.19146938E + 33
......:1.95548379
等等。
编辑2:
类型多项式定义为:
type, extends(bound_user_polynom) :: polynom
real(kind=kind(1.0D0)), allocatable, dimension(:) :: coeff
type(monomial),allocatable, dimension(:) :: monom
contains
procedure :: eval => poly_eval
procedure, private :: p_add
generic :: operator(+) => p_add
procedure, private :: p_subs
generic :: operator(-) => p_subs
end type
!constructor
interface polynom
module procedure construct_poly
end interface
在我的主程序中我打电话:
integral_result = integral(p(2), 2 , status)
答案 0 :(得分:0)
在comp.fortan的帮助下发现错误:
在:
userfun%eval(点(x = 2.,y = 2.,z = 0。))
我有一个未初始化的变量给了我这个奇怪的结果。 似乎其余的代码没有任何问题。
谢谢你, 扬