现在我正在用 FORTRAN 训练面向对象编程,我想使用包含函数指针的“类型”编写一个程序,如下所示的代码。然而,英特尔 Fortran 编译器 (v18) 显示编译错误,并表示 FUNCTION trig(self, x) 中的第一个参数应与类型绑定(bind)过程中定义的类型相同,包括传递绑定(bind)属性。
我对“现代”fortran 编程还不熟悉,所以我无法理解这个编译错误的含义。您能提供您的专业知识吗?
MODULE test_mod
!
use iso_fortran_env, only: REAL32, REAL64
!
implicit none
!
private
!
integer, parameter, private :: sp = REAL32
integer, parameter, private :: dp = REAL64
!
type, public :: t_obj
private
real( dp ) :: val = 1.0_dp
procedure( trig ), pass( self ), pointer, public :: trigFunc => null( )
contains
private
procedure, pass( self ), public :: setFunc
end type t_obj
!
ABSTRACT INTERFACE
FUNCTION trig( self, x )
class( t_obj ) :: self
real( kind( 1.0d0 ) ), intent( in ) :: x
real( kind( 1.0d0 ) ) :: trig
END FUNCTION trig
END INTERFACE
!
CONTAINS
!
FUNCTION cosFunc( self, x )
implicit none
class( t_obj ) :: self
real( dp ) :: x
real( dp ) :: cosFunc
cosFunc = cos( x ) * self%val
END FUNCTION cosFunc
!
FUNCTION sinFunc( self, x )
implicit none
class( t_obj ) :: self
real( dp ) :: x
real( dp ) :: sinFunc
sinFunc = sin( x ) * self%val
END FUNCTION sinFunc
!
SUBROUTINE setFunc( self, i )
implicit none
class( t_obj ), intent( inout ) :: self
integer :: i
if( i .eq. 1 ) then
self%trigFunc => cosFunc
else
self%trigFunc => sinFunc
end if
END SUBROUTINE setFunc
!
END MODULE test_mod
!
PROGRAM test_main
!
use test_mod
!
implicit none
type( t_obj ) :: obj
real( kind( 1.0d0 ) ) :: pihalf = datan( 1.0d0 ) * 2.0d0
!
call obj%setFunc( 1 )
write(*,*) obj%trigFunc( pihalf )
call obj%setFunc( 0 )
write(*,*) obj%trigFunc( pihalf )
!
END PROGRAM test_main
最佳答案
使用 INTEL Fortran 编译代码会出现此错误消息
error #8262: For a type-bound procedure that has the PASS binding attribute, the first dummy argument must have the same declared type as the type being defined. [SELF]
与抽象接口(interface)中的函数 trig( self, x )
相关。
正如 francescalus 所提到的,您的函数中缺少 import
语句。
添加它将解决您的问题:
ABSTRACT INTERFACE
FUNCTION trig( self, x )
import
class( t_obj ) :: self
real( kind( 1.0d0 ) ), intent( in ) :: x
real( kind( 1.0d0 ) ) :: trig
END FUNCTION trig
END INTERFACE
另请阅读此post .
希望有帮助吗?
关于oop - 现代 Fortran 中的面向对象编程,包括函数指针的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58761378/