分配派生类型的数组组件 [英] Allocating array components of derived types
问题描述
我有类似以下的内容
type BOPinfo
double precision, allocatable :: realQ4(:,:), realQ6(:,:)
end type BOPinfo
当元素是实数或整数标量时,我已经能够确定如何初始化派生类型中的元素.
I have been able to ascertain how to initialize elements in a derived type when the elements are real or integer scalars.
但是,我不知道如何告诉类型为BOPinfo
的变量realQ4
和realQ6
的大小,以及如何将它们初始化为零.有什么建议吗?
However, I can't figure out how to tell a variable of type BOPinfo
what the size of the arrays realQ4
and realQ6
are, and maybe how to initialize them to zero. Any suggestions?
推荐答案
可分配(或指针)类型的组件不能具有默认初始化.这适用于延迟形状数组和可分配/指针标量.可分配组件的初始状态始终为未分配".取而代之的是,将与对象的声明分开的各个组件分配并归零:
Allocatable (or pointer) type components cannot have default initialization. This applies to both deferred shape arrays and allocatable/pointer scalars. Allocatable components always have an initial status of "not allocated". Instead, one allocates and zeros the individual components separately from the object's declaration:
type(BOPinfo) test
integer n1, n2, m1, m2
allocate (test%realQ4(n1,m1), test%realQ6(n2,m2))
test%realQ4 = 0
test%realQ6 = 0
这与默认(或显式)初始化不同,并且还可以在结构构造函数中设置值(如另一种答案).
This is different from default (or explicit) initialization, and one may also set the value in a structure constructor (as in another answer).
在Fortran 2003中,还有其他用于动态大小的方法,包括参数化派生类型(目前在最新的编译器版本中得到广泛支持).
Under Fortran 2003 there are other approaches for the dynamic size, including parameterized derived types (which are now widely supported in recent compiler versions).
这篇关于分配派生类型的数组组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!