Fortran中受保护的全局变量(Protected global variables in Fortran)

编程入门 行业动态 更新时间:2024-10-22 20:38:53
Fortran中受保护的全局变量(Protected global variables in Fortran)

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

I wonder if there is a way of having a global variable in Fortran, which can be stated as some kind of 'protected'. I am thinking of a module A that contains a list of variables. Every other module or subroutine that uses A can use it's variables. If you know what the value of the variable is, you could use parameter to achieve that it can't be overwritten. But what if you have to run code first to determine the variables value? You could not state it as parameter since you need to change it. Is there a way to do something similar but at a specific point at runtime?

最满意答案

您可以在模块中使用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

You could use the PROTECTEDattribute in a module. It has been introduced with the Fortran 2003 standard. The procedures in the module can change PROTECTED objects, but not procedures in modules or programes that USE your module.

Example:

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

更多推荐

本文发布于:2023-04-27 16:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327167.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:全局变量   Fortran   Protected   variables   global

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!