2017-07-25 110 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

相關問題