我想知道在Fortran中是否有一种方法来拥有一个全局变量,它可以被声明为某种“保护”。我正在考虑一个包含变量列表的模块A。其他使用A的模块或子例程都可以使用它的变量。如果你知道变量的值是什么,你可以使用参数来实现它不能被覆盖。但是,如果您必须先运行代码来确定变量的值,该怎么办呢?您不能将其声明为参数,因为您需要更改它。有没有一种方法可以在运行时在特定的时间点做类似的事情?
发布于 2013-02-22 17:23:30
您可以在模块中使用PROTECTED属性。它是在Fortran 2003标准中引入的。模块中的过程可以更改受保护的对象,但不能更改模块中的过程或使用模块的程序。
示例:
module m_test
integer, protected :: a
contains
subroutine init(val)
integer val
a = val
end subroutine
end module m_test
program test
use m_test
call init(5)
print *, a
! if you uncomment these lines, the compiler should flag an error
!a = 10
!print *, a
call init(10)
print *, a
end program https://stackoverflow.com/questions/15020460
复制相似问题