Fortran 中的函数和子程序指针使用
在 Fortran 中,可以使用过程指针(procedure pointers)来指向函数或子程序,这提供了类似于函数指针的功能。下面我将通过示例程序说明如何在 Fortran 中使用函数和子程序指针。
1. 函数指针示例
program function_pointer_example
implicit none
! 声明函数指针接口
abstract interface
function func_interface(x) result(y)
real, intent(in) :: x
real :: y
end function func_interface
end interface
! 声明函数指针
procedure(func_interface), pointer :: f_ptr => null()
! 声明要指向的函数
real :: a, b
! 将函数指针指向不同的函数
f_ptr => square
a = f_ptr(2.0)
print *, "Square of 2.0 is ", a
f_ptr => cube
b = f_ptr(2.0)
print *, "Cube of 2.0 is ", b
contains
function square(x) result(y)
real, intent(in) :: x
real :: y
y = x * x
end function square
function cube(x) result(y)
real, intent(in) :: x
real :: y
y = x * x * x
end function cube
end program function_pointer_example
2. 子程序指针示例
program subroutine_pointer_example
implicit none
! 声明子程序指针接口
abstract interface
subroutine sub_interface(x, y)
real, intent(in) :: x
real, intent(out) :: y
end subroutine sub_interface
end interface
! 声明子程序指针
procedure(sub_interface), pointer :: s_ptr => null()
! 声明变量
real :: input, output
! 将子程序指针指向不同的子程序
input = 3.0
s_ptr => increment
call s_ptr(input, output)
print *, "Incremented value is ", output
s_ptr => decrement
call s_ptr(input, output)
print *, "Decremented value is ", output
contains
subroutine increment(x, y)
real, intent(in) :: x
real, intent(out) :: y
y = x + 1.0
end subroutine increment
subroutine decrement(x, y)
real, intent(in) :: x
real, intent(out) :: y
y = x - 1.0
end subroutine decrement
end program subroutine_pointer_example
3. 函数指针数组示例
program function_pointer_array
implicit none
! 声明函数指针接口
abstract interface
function math_func(x) result(y)
real, intent(in) :: x
real :: y
end function math_func
end interface
! 声明函数指针数组
procedure(math_func), pointer :: func_array(:) => null()
! 分配函数指针数组
allocate(func_array(3))
! 将函数指针指向不同的函数
func_array(1) => square
func_array(2) => cube
func_array(3) => square_root
! 使用函数指针数组
print *, "Square of 4.0 is ", func_array(1)(4.0)
print *, "Cube of 4.0 is ", func_array(2)(4.0)
print *, "Square root of 4.0 is ", func_array(3)(4.0)
! 释放内存
deallocate(func_array)
contains
function square(x) result(y)
real, intent(in) :: x
real :: y
y = x * x
end function square
function cube(x) result(y)
real, intent(in) :: x
real :: y
y = x * x * x
end function cube
function square_root(x) result(y)
real, intent(in) :: x
real :: y
y = sqrt(x)
end function square_root
end program function_pointer_array
关键点说明
- 抽象接口:必须使用
abstract interface
块定义函数或子程序的接口 - 指针声明:使用
procedure(interface_name), pointer
语法声明过程指针 - 指针赋值:使用
=>
操作符将指针指向具体的函数或子程序 - 调用:通过指针调用函数或子程序与直接调用方式相同
- 空指针:初始化时应设为
null()
,使用前应检查是否关联
这些示例展示了 Fortran 中过程指针的基本用法,可以用于实现回调函数、策略模式等高级编程技术。