【问题标题】:Protected global variables in FortranFortran 中受保护的全局变量
【发布时间】:2013-02-07 20:25:54
【问题描述】:

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

【问题讨论】:

    标签: global-variables fortran protected


    【解决方案1】:

    您可以在模块中使用PROTECTEDattribute。它是随 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  
    

    【讨论】:

      猜你喜欢
      • 2013-09-26
      • 2021-12-27
      • 2011-08-02
      • 1970-01-01
      • 2013-11-19
      • 2014-01-25
      • 1970-01-01
      • 2023-02-02
      • 2015-03-19
      相关资源
      最近更新 更多