直接使用派生类型的成员变量而不使用百分号的更有效的方法



如使用不带%的fortran派生类型变量所示,我们可以使用associate来避免使用百分号。示例如下:

program test
type z_type
real x,y
end type z_type
type(z_type) :: z
associate (x=>z%x)
associate (y=>z%y)
x=10
y=10
write(6,*)z%x,z%y
end associate
end associate
end

但是,如果在派生类型中有太多成员变量,是否存在"有效的"成员变量?方法让我得到什么上面的"关联";方法呢?
谢谢。更新:问题是我正在重构遗留代码,其中我需要将许多变量打包到派生类型结构中。但是我希望我不需要在前面代码块中添加派生数据名称后面跟着%符号的每个变量。

我想,你可以使用指针,但这有点不自然。

program test
implicit none
type z_type
real x, y
end type z_type
type(z_type), target :: z
real, pointer :: x, y
x => z%x
y => z%y
x = 10
y = 20
write( *, * ) z
end program test

如果变量都是一种类型,那么Fortran数组是非常有效的:

program test
implicit none
type z_type
real x(2)
end type z_type
type(z_type) z
z%x = [ 10, 20 ]
write( *, * ) z
end program test

总的来说,让z_type成为一个合适的类,有自己的类型绑定过程(又名成员函数),并让它成为面向对象的编程可能会更好。

module modz
implicit none
type z_type
real x, y
contains
procedure write_me
end type z_type
contains
subroutine write_me( this )
class(z_type), intent(in) :: this
write( *, *) this%x, this%y
end subroutine write_me
end module modz
!=======================================
program test
use modz
implicit none
type(z_type) :: z = z_type( 10, 20 )
call z%write_me
end program test

最新更新