正如标题所述,我想要directly修改我通过从函数检索的指针访问的数据。函数返回的引用出现在 l.h.s 上。赋值(=)在 C++ 中没有问题,但 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]]
wehre XX
将参考null()
.
Update:我使用的是 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
这并不完全是我想要的,但对于我的申请来说已经足够了。