File tree Expand file tree Collapse file tree 1 file changed +87
-0
lines changed Expand file tree Collapse file tree 1 file changed +87
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 过程指针
2
+
3
+ 指针也可以指向过程,这时候需要先声明指针的接口,用于限制指针的类型,也就是在之前的章节中我们提到的` abstract interface `
4
+
5
+ ``` fortran
6
+ module proc_pointer_mod
7
+ implicit none
8
+ abstract interface
9
+ real(8) function func1d(x) result(res)
10
+ real(8),intent(in)::x
11
+ end function func1d
12
+ end interface
13
+ contains
14
+ real(8) function mysin(x) result(res)
15
+ real(8),intent(in)::x
16
+ res=sin(x)
17
+ end function mysin
18
+ real(8) function myexp(x) result(res)
19
+ real(8),intent(in)::x
20
+ res=exp(x)
21
+ end function myexp
22
+ real(8) function mycos(x) result(res)
23
+ real(8),intent(in)::x
24
+ res=cos(x)
25
+ end function mycos
26
+ end module proc_pointer_mod
27
+
28
+ program main
29
+ use proc_pointer_mod
30
+ implicit none
31
+ procedure(func1d),pointer::ptr=>null()
32
+ ptr=>mysin
33
+ write(*,*)ptr(1.0_8)
34
+ ptr=>myexp
35
+ write(*,*)ptr(1.0_8)
36
+ ptr=>mycos
37
+ write(*,*)ptr(1.0_8)
38
+ end program main
39
+ ```
40
+ - 不能使用过程指针指向通用函数名。由于Fortran的内置函数都是经过重载的通用函数,所以也不能用过程指针指向内置函数
41
+
42
+ 如果定义一个过程指针数组,则需要使用到自定义类型,同时也要指定` nopass ` 关键字,用来表示不需要绑定该类型作为第一个虚参传递。
43
+ ``` fortran
44
+ module proc_pointer_mod
45
+ implicit none
46
+ abstract interface
47
+ real(8) function func1d(x) result(res)
48
+ real(8),intent(in)::x
49
+ end function func1d
50
+ end interface
51
+ type ptrfunc
52
+ procedure(func1d),pointer,nopass::ptr
53
+ end type ptrfunc
54
+ contains
55
+ real(8) function mysin(x) result(res)
56
+ real(8),intent(in)::x
57
+ res=sin(x)
58
+ end function mysin
59
+ real(8) function myexp(x) result(res)
60
+ real(8),intent(in)::x
61
+ res=exp(x)
62
+ end function myexp
63
+ real(8) function mycos(x) result(res)
64
+ real(8),intent(in)::x
65
+ res=cos(x)
66
+ end function mycos
67
+ end module proc_pointer_mod
68
+
69
+ program main
70
+ use proc_pointer_mod
71
+ implicit none
72
+ type(ptrfunc)::a(3)
73
+ integer::i
74
+ a(1)%ptr=>mysin
75
+ a(2)%ptr=>myexp
76
+ a(3)%ptr=>mycos
77
+ write(*,*)(a(i)%ptr(1.0_8),i=1,3) !此处使用隐式循环输出
78
+ end program main
79
+ ```
80
+
81
+ - 使用过程指针后,一些操作需要转向运行时确定,所以编译器无法进行更加激进的优化(内联inline),代码的运行速度有可能会降低。
82
+
83
+ ## 习题
84
+ - 思考为什么不使用` procedure(func1d),pointer::ptr(:) ` 来定义过程指针数组
85
+
86
+
87
+
You can’t perform that action at this time.
0 commit comments