File tree 1 file changed +36
-3
lines changed 1 file changed +36
-3
lines changed Original file line number Diff line number Diff line change @@ -6,32 +6,65 @@ Fortran2003开始支持过程绑定,将子程序或者函数与对应的类型
6
6
7
7
过程绑定中, 对应子过程的虚参声明需要使用` class ` 关键字。同时在类型的定义中使用` procedure ` 关键字将其绑定,使用` contains ` 将类型和函数分开。
8
8
9
+ ## 析构函数
10
+
11
+ 程序运行结束之后,这个对象需要释放,此时使用` final ` 关键字可以指定一个函数为析构函数。当释放的时候就会调用这个函数。
12
+
9
13
``` fortran
10
14
module vector_mod
11
15
implicit none
12
16
type vector_t
13
17
real,allocatable::x(:)
18
+ integer::capacity
19
+ integer::size
14
20
contains
15
21
procedure,pass:: init => vector_init
22
+ procedure,pass:: append => vector_append
23
+ final :: vector_final
16
24
end type vector_t
17
25
contains
18
26
subroutine vector_init(this,n)
19
27
class(vector_t),intent(inout)::this
20
28
integer,intent(in)::n
21
29
allocate(this%x(n))
30
+ this%size=0
31
+ this%capacity=n
22
32
end subroutine vector_init
33
+
34
+ subroutine vector_append(this,val)
35
+ class(vector_t),intent(inout)::this
36
+ real,intent(in)::val
37
+ this%size=this%size+1
38
+ this%x(this%size)=val
39
+ end subroutine vector_append
40
+
41
+ subroutine vector_final(this)
42
+ type(vector_t),intent(inout):: this !此处是type 不是class
43
+ if(allocated(this%x))deallocate(this%x) !释放可分配数组
44
+ this%size=0
45
+ this%capacity=0
46
+ write(*,*)"call final"
47
+ end subroutine vector_final
23
48
end module vector_mod
24
49
25
50
program main
26
51
use vector_mod
27
52
implicit none
28
- type(vector_t)::v
29
- call v%init(10)
53
+ block
54
+ type(vector_t)::v
55
+ call v%init(10)
56
+ end block !离开作用域时会调用析构函数
57
+ write(*,*)"done"
30
58
end program main
31
-
32
59
```
60
+
33
61
- ` pass ` 关键字用来指定在调用的过程中,被调用的类型会** 自动传递为第一个虚参** ,与之对应的还有` nopass ` ,不自动传递
34
62
- ` pass(this) ` 关键字也可以带具体的参数,用于指定哪个虚参被自动传递。当你的函数中有多个虚参都是当前类型的时候,你可以指定任意一个。
35
63
- 使用` => ` 可以为绑定的过程重命名。
36
64
- 被绑定的变量名尽量使用` this ` 或者` self ` (与其他语言的习惯相符)
37
65
66
+ ## 习题
67
+ - vector的` append ` 函数并没有考虑超过` capacity ` 的情况。重写这个函数,使其可以在元素超出的时候自动扩容。
68
+ - (附加题)使用` move_alloc ` 子程序完成上述功能。
69
+
70
+
You can’t perform that action at this time.
0 commit comments