问题描述
我有一个模块,该模块定义具有某些属性的类和一个作为函数的方法( proc1
).另一个模块定义了一个函数( proc2
),该函数使用一个参数评估函数,并给出指向该函数和参数的指针.在主程序中,我想定义一个指向类的方法( proc1
)的函数指针( fun
),以便评估 fun(x)
等同于评估 obj1%proc1(x)
.那可能吗?
I have a module that defines a class with some attributes and a method (proc1
) which is a function. Another module defines a function (proc2
) that evaluates a function with one argument, given a pointer to that function and the argument. In the main program, I would like to define a function pointer (fun
) which points to the class' method (proc1
) such that evaluating fun(x)
would be equivalent to evaluating obj1 % proc1(x)
. Is that possible?
我的编译器gfortran 7.3抱怨
My compiler, gfortran 7.3, complains that
,其语法如下.
module objmod
implicit none
! object with some data and a method
type obj
real :: a, b, c
contains
procedure, pass(self) :: proc1
end type obj
contains
! method which uses object and a variable
pure real function proc1(self, var)
class(obj), intent(in) :: self
real, intent(in) :: var
proc1 = var * (self % a + self % b + self % c)
end function proc1
end module objmod
module funmod
implicit none
contains
! function that evaluates fun(a), or does more complicated stuff
real function proc2(funptr, a)
procedure(real), pointer :: funptr
real, intent(in) :: a
proc2 = funptr(a)
end function proc2
end module funmod
program funPtr
use objmod
use funmod
implicit none
type(obj) :: obj1
real :: a, x
procedure(real), pointer :: fun
obj1 % a = 1.0
obj1 % b = 2.0
obj1 % c = 3.0
a = -1.5
fun => obj1 % proc1 ! function pointer to fun(x) = proc1(obj1, x)
x = proc2(fun, a)
print *, x
end program funPtr
推荐答案
不,您不能这样做.该标准说,对于指针分配的proc-target:
No, you can't do this. The standard says, for a proc-target of pointer assignment:
在您的示例中, obj1%proc1
都不是这些.如果为 fun
提供了显式接口,则可以将指针分配给 proc1
(即实际过程,而不是类型组件).当然,这样做会丢失传递的对象方面.
In your example, obj1%proc1
is none of these. You COULD pointer assign to proc1
(that is, the actual procedure and not the type component) if you gave fun
an explicit interface. Of course, you lose the passed object aspect if you do this.
问题在于函数指针没有类型绑定过程的上下文.
The issue is that a function pointer doesn't have the context of the type-bound procedure.
这篇关于如何指向fortran中的类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!