Fortran中t1Class内t2Class对象因intent(out)失效问题求助
Fortran OOP中类成员对象无法跨成员函数访问
我希望在t1Class中包含一个t2Class对象,使t2Class内的变量能在t1Class的成员函数间共享。但在initialise函数中分配t2Class对象后,无法在test1函数中使用该对象,提示访问未定义内容的错误。
主程序代码
program test use t1Class_mod implicit none class(t1Class),allocatable :: obj allocate(obj) print*, "obj%initialise" call obj%initialise print*, "obj%test1" call obj%test1 end
t1Class模块代码
module t1Class_mod use t2Class_mod implicit none type :: t1Class class(t2Class),allocatable :: test contains procedure :: initialise => initialise procedure :: test1 => test1 end type t1Class contains subroutine initialise(this) implicit none class(t1Class),intent(out) :: this allocate(this%test) this%test%n = 1 end subroutine initialise subroutine test1(this) implicit none class(t1Class),intent(out) :: this print*, "test1",this%test%n end subroutine test1 end
t2Class模块代码
module t2Class_mod implicit none type :: t2Class integer :: n end type t2Class contains end
问题解决
问题源于类成员函数中this参数的*intent(out)*属性:当参数声明为intent(out)时,Fortran会自动将传入的对象完全重置,包括释放所有已分配的可分配成员变量。这意味着在initialise中分配的this%test,会在进入test1函数时被释放,导致访问未定义内容。
只需将两个成员函数中的this参数的intent(out)改为*intent(inout)*即可:
修改后的成员函数代码:
subroutine initialise(this) implicit none class(t1Class),intent(inout) :: this allocate(this%test) this%test%n = 1 end subroutine initialise subroutine test1(this) implicit none class(t1Class),intent(inout) :: this print*, "test1",this%test%n end subroutine test1
内容的提问来源于stack exchange,提问作者DongAlpha
相关产品推荐
相关产品推荐

