2017-07-25 107 views
1

当我尝试将扩展类型的指针传递给需要指向父类型类的指针的例程时,出现类型不匹配错误。但是,在第二种情况下,伪参数不是指针,它编译得很好。将子类型的指针传递给采用父类指针的伪参数

child_type是一个parent_type类,它们都有指针属性,所以一切似乎都匹配,并且它在哑参数不是指针时起作用。

那么,为什么它会失败,如果哑参是一个指针?

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 

回答

2

在指针伪参数情况下,过程可以重新关联指针到一个对象,它是一个不同的扩展类型的到实际的论点。这不是一个明智的做法,所以语言禁止它。

一般来说,当你想要做一些与参数的指针关联状态相关的参数时,虚拟参数应该只是指针。

+0

如何将指针关联到不是父类型的扩展的东西?如果指针是子类型,那么它指向的任何东西也不得不是父类型的扩展? – Exascale

+1

在过程中,指针的声明类型是父类型。在这个过程中,指针可以指向另一个类型,它是你的子类型的一个* sibling *(或者一个兄弟的扩展) - 通用的父类,不同的扩展。然后当程序结束并执行回到调用范围时,就会出现混乱。 – IanH

相关问题