这取决于你所说的“返回”是什么意思。
本身提供的例子
t%a([1,2,5]) ! Using syntax offered by Fortran 2003
doesn't return任何东西:这是一个子对象。通过引用该子对象,我们可以做各种事情:
print *, t%a([1,2,5])
t%a([1,2,5]) = 27
t%a([1,2,5]) = sin(real(t%a([1,2,5])))
但仍然没有“回归”的概念。至关重要的是,正如我们将看到的,这些不是表达。
Coming to the question, can t[]
, t()
, t{}
mean something, then the answer is, simply, "no".* You may want, for example, to say:
t[1,2,5] = 1
to mean
t%a[1,2,5] = 1
但这不是需要考虑的事情。
可以创建一个像这样的表达式
print *, t%ref([1,2,5])
但我们完全处于无法定义的领域。
然而,正如您现在提到指针一样,还有更多要说的。虽然首选语法t[1]
or t["first"]
不可用时,我们仍然可以选择类型绑定过程。例如,函数调用t%ref("first")
很可能能够返回指向第一个元素的指针t%a
。例如,t%ref(1)
可能就像
module reference
implicit none
type custom
integer, dimension(:), allocatable :: a
contains
procedure ref
end type custom
contains
function ref(t, idx)
class(custom), target, intent(in) :: t
integer, intent(in) :: idx
integer, pointer :: ref
ref => t%a(idx)
end function ref
end module reference
use reference
implicit none
type(custom), target :: t
integer, pointer :: b
t%a = [1, 2, 3, 4, 5]
print *, t%a
b => t%ref(1) ! Fortran 2008 allows direct assignment
b = 8 ! but compiler support is very limited.
print *, t%a
end
如果需要的话ref
可以通用,以便t%ref("first")
(等)是可以接受的。
* I'm basing that on the fact that here t
is a scalar. However, as mentioned by Vladimir F in a comment ()
and []
potentially do mean things. The first relates to arrays and the second to co-arrays. Syntax, then, is an issue, but this answer looks more at the mechanism than syntax.