如标题所述,我想直接修改通过从函数中检索的指针访问的数据。在 C++ 中,出现在赋值(=)的 lhs 上的函数返回的引用是没有问题的,但以下 fortran 错误中的最小示例:
module test_mod
implicit none
integer, target :: a=1, b=2, c=3 ! some member variables
contains
function get(i)
integer, pointer :: get
integer, intent(in) :: i
select case (i)
case (1)
get => a
case (2)
get => b
case (3)
get => c
end select
end function get
end module test_mod
program test
use test_mod
implicit none
integer, pointer :: i_p
!> prints out 1 2 3
print*, get(1), get(2), get(3)
!> this is what I want but I get the error
!> Error: 'get' at (1) is not a variable
get(2) = 5
!> this works but is not what I want
i_p => get(2)
i_p = 5
end program test
有没有办法完成这种行为;也许我缺少一些属性?我想绕过编写任何设置器例程,例如
set(i,value)
因为它应该模仿数组的外观。在我的应用程序中,成员变量a,b,c
实际上是不同大小的数组
a = [a1, a2, a3]
b = [b1, b2]
c = [c1]
我希望吸气剂get(i,j)
模仿一个指针矩阵
j = 1 2 3
i = 1: [[a1, a2, a3],
i = 2: [b1, b2, XX],
i = 3: [c1, XX, XX]]
我们XX
将引用null()
.
更新: 我正在使用 gfortran(版本 5.2.0),部署机器只有从 4.6.x 及更高版本开始的版本。因此,很遗憾我无法使用建议的 fortran 2008 标准功能。是否可以在没有开箱即用的编译器支持的情况下模仿上述行为?
更新2: 所以我最终实现了一个结构如下
type Vec_t
integer, allocatable, dimension(:) :: vec
end type Vec_t
type(Vec_t), allocatable, dimension(:), target :: data
我这样初始化(我在最后提到的三角矩阵应用程序)
allocate(data(max))
do i=1,max
allocate(data(i)%vec(i))
end do
我通过它访问并写入它
print*, data(2)%vec(1)
data(2)%vec(1) = 5
这不正是我所追求的,但对于我的申请来说已经足够了。