Skip to content

Commit 3ffaf28

Browse files
authored
Update ch07-01-procbind.md
1 parent 97cedf8 commit 3ffaf28

File tree

1 file changed

+36
-3
lines changed

1 file changed

+36
-3
lines changed

src/ch07-01-procbind.md

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,32 +6,65 @@ Fortran2003开始支持过程绑定,将子程序或者函数与对应的类型
66

77
过程绑定中, 对应子过程的虚参声明需要使用`class`关键字。同时在类型的定义中使用`procedure`关键字将其绑定,使用`contains`将类型和函数分开。
88

9+
## 析构函数
10+
11+
程序运行结束之后,这个对象需要释放,此时使用`final`关键字可以指定一个函数为析构函数。当释放的时候就会调用这个函数。
12+
913
``` fortran
1014
module vector_mod
1115
implicit none
1216
type vector_t
1317
real,allocatable::x(:)
18+
integer::capacity
19+
integer::size
1420
contains
1521
procedure,pass:: init => vector_init
22+
procedure,pass:: append => vector_append
23+
final :: vector_final
1624
end type vector_t
1725
contains
1826
subroutine vector_init(this,n)
1927
class(vector_t),intent(inout)::this
2028
integer,intent(in)::n
2129
allocate(this%x(n))
30+
this%size=0
31+
this%capacity=n
2232
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
2348
end module vector_mod
2449
2550
program main
2651
use vector_mod
2752
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"
3058
end program main
31-
3259
```
60+
3361
- `pass`关键字用来指定在调用的过程中,被调用的类型会**自动传递为第一个虚参**,与之对应的还有`nopass`,不自动传递
3462
- `pass(this)`关键字也可以带具体的参数,用于指定哪个虚参被自动传递。当你的函数中有多个虚参都是当前类型的时候,你可以指定任意一个。
3563
- 使用`=>`可以为绑定的过程重命名。
3664
- 被绑定的变量名尽量使用`this`或者`self`(与其他语言的习惯相符)
3765

66+
## 习题
67+
- vector的`append` 函数并没有考虑超过`capacity`的情况。重写这个函数,使其可以在元素超出的时候自动扩容。
68+
- (附加题)使用`move_alloc`子程序完成上述功能。
69+
70+

0 commit comments

Comments
 (0)