问题描述
我想访问数组的元素使用子程序sum_real一个一个阵列派生类型。这就是:在为所有的人在举重第一项之和。
I would like to access the the elements of an array in a an arrayed derived type using the subroutine sum_real. That is: sum over first entry in the weight for all people.
type my_type
real, dimension(:), allocatable :: weight
real :: total_weight
end type my_type
type (my_type), dimension (:), allocatable :: people
type (my_type) :: answer
allocate (people (2))
allocate (people (1)%weight(2))
allocate (people (2)%weight(2))
people (1) % weight(1) = 1
people (2) % weight(1) = 1
people (1) % weight(2) = 3
people (2) % weight(2) = 3
call sum_real ( people (:) % weight(1), answer % total_weight )
我想要做的是类似于派生类型的,除非我有在阵列派生类型,而不是一个单一元素的数组分配的事实。
What I want to do is similar to the answer found in Array of derived type: select entry, except for the fact that I have an allocated array in an arrayed derived type instead of an single element.
不过,我得到一个编译器错误:
But, I get a compiler error:
错误#7828:该部分名称的一部分,裁判有非零秩的右边有ALLOCATABLE属性(6.1.2)。 【重量】
error #7828: The part-name to the right of a part-ref with nonzero rank has the ALLOCATABLE attribute (6.1.2). [WEIGHT]
推荐答案
在尝试什么是不可能的,如果你的组件是可分配的。参考( 6.1.2
)实际上是官方标准文件的引用,禁止这一点。
What you try is not possible if your component is allocatable. The reference (6.1.2
) is actually a reference to the official standard documents, which prohibits this.
原因很简单,分配组件(标量或阵列)存储在内存比派生类型本身的不同部分。因此,如果你写
The reason is simple, the allocatable components (scalar or arrays) are stored in a different part of memory than the derived type itself. Therefore if you write
sum(people%total_weight)
或
people%total_weight = 0
是 total_weight
没有问题,是不是分配的,它存储派生类型中,编译器只是去在一个简单的循环,并设置一个字段陆续零。你可以知道每一个地址%totalweight
事先
it is no problem, total_weight
is not allocatable, it is stored within the derived type and the compiler just goes in a simple loop and sets one field after another to zero. You can know the address of each %totalweight
beforehand.
在另一方面
sum(people%weight)
或
people%weight = 0
每个%重量
存储在别处,你没有任何简单的公式来计算,其中为每个%重量(I)
。
each %weight
is stored elsewhere and you don't have any simple formula to compute where is each %weight(i)
.
的溶液可以是,固定阵列的大小,如果可能的话
The solution is either, to fix the size of the array, if possible
real, dimension(2) :: weight
或使用do循环
s = 0
do i = 1, size(people)
S = S + sum(people(i)%weight)
end do
这篇关于手柄数组派生类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!