2013-02-22 138 views
4

我想知道在Fortran中是否有一种全局变量的方式,可以将其称为某种“受保护”类型。我正在考虑一个包含变量列表的模块A.使用A的每个其他模块或子例程都可以使用它的变量。如果你知道变量的值是什么,你可以使用参数来实现它不能被覆盖。但是如果你必须先运行代码来确定变量值呢?由于您需要更改它,因此您无法将其指定为参数。有没有办法做类似的事情,但在运行时的特定点?Fortran中受保护的全局变量

回答

12

您可以在模块中使用PROTECTED属性。它已在Fortran 2003标准中引入。 模块中的程序可以更改PROTECTED对象,但不能更改使用模块的模块或程序中的程序。

实施例:

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