我正在尝试使用 % 运算符访问数据类型的元素,但结果为零。 我在下面有一些示例代码。
该行print*, t%tsum
始终打印出零。 但是,当我在子例程中打印 tsum 时,它应该是这样的。
MODULE statistics
PUBLIC :: TimeMarker , start , finish , avgTime , begin , end_ , tsum , counts
TYPE TimeMarker
REAL*8 :: begin , end_ , tsum
INTEGER :: counts = 0
CONTAINS
PROCEDURE :: start => start_time
PROCEDURE :: finish => finish_time
PROCEDURE :: avgTime => averageTime
END TYPE TimeMarker
CONTAINS
SUBROUTINE start_time(this)
CLASS(timeMarker) , INTENT(INOUT) :: this
CALL CPU_TIME(begin)
END SUBROUTINE start_time
SUBROUTINE finish_time(this)
CLASS(timeMarker) , INTENT(INOUT) :: this
CALL CPU_TIME(end_)
tsum = tsum + end_ - begin
counts = counts + 1
END SUBROUTINE finish_time
SUBROUTINE averageTime(this)
CLASS(timeMarker) , INTENT(INOUT) :: this
WRITE(*,*) "Average time : " , tsum/counts
END SUBROUTINE averageTime
END MODULE statistics
program test
use statistics
implicit none
type(TimeMarker) :: t
integer :: n , m
real*8 :: a
do m=1,50
call t%start
do n=1,20000000
a = sqrt(a)
end do
print*, t%tsum
end do
call t%avgTime
end program test
在类型绑定过程中,传递对象的组件仍使用语法argument_name % component_name
引用。 传递的对象没有隐式的"this"变量,就像在其他语言中可能会找到的那样。 您已使用this
作为传递的参数的名称 - 因此例如,必须将 begin 组件引用为this % begin
,而不仅仅是begin
。
在模块的作用域中,隐式类型是有效的 - 模块没有隐式 NONE 语句。 因此,在类型绑定过程中操作的变量是隐式声明的模块变量,这意味着编译器不会报告任何错误。
示例代码中还有其他逻辑错误,一旦修复了组件引用,就需要处理这些错误。
(%
不是 Fortran 中的运算符,它只是语法的一部分。