Fortran 将子类型的指针传递给接受父类指针的伪参数
当我试图将扩展类型的指针传递给一个例程,该例程将指针传递给父类型的类时,我会得到一个类型不匹配错误。但是,在第二种情况下,如果伪参数不是指针,则它可以很好地编译 child_类型是parent_类型的一个类,它们都有pointer属性,因此所有内容似乎都匹配,并且当伪参数不是指针时,它会工作 那么,如果伪参数是指针,为什么它会失败呢Fortran 将子类型的指针传递给接受父类指针的伪参数,fortran,Fortran,当我试图将扩展类型的指针传递给一个例程,该例程将指针传递给父类型的类时,我会得到一个类型不匹配错误。但是,在第二种情况下,如果伪参数不是指针,则它可以很好地编译 child_类型是parent_类型的一个类,它们都有pointer属性,因此所有内容似乎都匹配,并且当伪参数不是指针时,它会工作 那么,如果伪参数是指针,为什么它会失败呢 module wrong_type_test implicit none type parent_type integer :: a end
module wrong_type_test
implicit none
type parent_type
integer :: a
end type parent_type
type, extends(parent_type) :: child_type
integer :: b
end type child_type
contains
subroutine ptr_test(parent_ptr)
class(parent_type), pointer, intent(inout) :: parent_ptr
print *, "test"
end subroutine ptr_test
subroutine non_ptr_test(parent)
class(parent_type), intent(inout) :: parent
print *, "test"
end subroutine non_ptr_test
end module wrong_type_test
program test
use wrong_type_test
implicit none
class(child_type), pointer :: child_ptr
call non_ptr_test(child_ptr) !this works
call ptr_test(child_ptr) !this doesn't work
end program test
ifort错误:
select_type_pointer_test.f90(33): error #6633: The type of the actual argument differs from the type of the dummy argument. [CHILD_PTR]
call ptr_test(child_ptr)
gfortran错误:
Error: Actual argument to 'parent_ptr' at (1) must have the same declared type
在指针伪参数的情况下,过程可以将指向不同扩展类型的对象的指针重新关联到实际参数。这样做是不明智的,因此语言禁止这样做
通常,只有当您想执行与参数的指针关联状态相关的操作时,伪参数才应该是指针。如何将指针关联到非父类型扩展的对象?如果指针是子类型的,那么它指向的任何东西不也必须是父类型的扩展吗?在过程中,指针的声明类型是父类型。在过程内部,指针可以指向另一种类型,即子类型的同级(或同级的扩展)-公共父级,不同扩展。然后,当过程结束并且执行回到调用范围时,混乱随之发生。