将常量命名为派生数据类型的组件

问题描述 投票:6回答:4

似乎Fortran 90不允许派生数据类型中的命名常量。这是真的?以下代码不起作用。

program my_prog
implicit none
   type :: my_type
      integer, parameter :: a = 1
      real(kind(1.d0))   :: b
   end type my_type
   type (my_type) :: complex_type
end program my_prog

编译器说在派生类型定义中不允许使用参数语句。

当我删除parameter关键字一切正常。但是,我怎样才能确保组件a在其他地方没有被修改?

fortran constants derived-types
4个回答
5
投票

使常量(参数)成为主程序的本地实体而不是类型。如果希望更多地控制常量的标识符的可见性和范围,则将常量放在模块中。


5
投票

根据标准,不允许。组件属性说明符可能只是pointerdimension用于Fortran 90/95(第4.4.1节),另外allocatable用于Fortran 2003(第4.5.3节),另外还有codimensioncontiguousfor Fortran 2008(第4.5.4.1节)。

你可以得到文件here

我遇到了与target说明符类似的问题,这也是不允许的。

编辑:为什么不尝试private组件?

module typedef
  type :: my_type
    integer, private :: a_int = 1
    real(kind(1.d0)) :: b
  contains
    procedure :: a
  end type my_type

contains
  function a(complex_type)
    class(my_type),intent(in) :: complex_type
    integer :: a
    a = complex_type%a_int
  end function
end module

program my_prog
  use typedef
  implicit none

  type (my_type) :: complex_type

  complex_type%b = 2.d0 ! This should work
  write(*,*) complex_type%a(), complex_type%b

!  complex_type%a_int = 3    ! This should fail

end program my_prog

3
投票

问题是:你为什么要这样做?

想象一下,你想要创建一个1000个值my_type的数组。结果是,a的值将被存储1000次。这浪费了近4kb的内存(假设是int4)。更好的方法是在相应的模块中定义参数。

顺便说一句,在Clerman和Spector的Modern Fortran一书中,规则编号133指出,你应该在自己的模块中定义每个派生类型。对于这样的常数,这将是一个很好的地方。


1
投票

您可以将其定义为private并生成get()函数,但不能生成set()函数。通过这种方式,您的数据将得到很好的封装。

© www.soinside.com 2019 - 2024. All rights reserved.