2017-06-13 44 views
1

我想重載一個我想用於多態指針的類型的賦值。我不知道指針在運行時持有的實際子類型。 但下面的示例代碼重新奇怪編譯器錯誤,我得到:帶指針的Fortran賦值過載

module example 

type :: base_class 
    real(4) :: some_garbage 
contains 

end type 

type, extends(base_class) :: sub_class 
    real(4) :: even_more_garbage 
contains 

end type 

type :: main_operations_t 
    class(base_class), pointer :: basic_pointer 
    class(base_class), pointer :: pointer_array(:) 
contains 
    procedure :: main_operations 
end type 

interface assignment(=) 
    module procedure assign_base_class 
end interface 

contains 

subroutine assign_base_class(result_object, input_object) 
implicit none 
    class(base_class), pointer, intent(out) :: result_object 
    class(base_class), pointer, intent(in) :: input_object 
    result_object%some_garbage = input_object%some_garbage 
end subroutine 

subroutine main_operations(this) 
implicit none 
    class(main_operations_t) :: this 
    class(base_class), pointer :: hack 

    allocate(this%basic_pointer) 
    allocate(this%pointer_array(2)) 

    this%basic_pointer%some_garbage = 0.0 
    this%pointer_array(1)%some_garbage = 1.0 
    this%pointer_array(2)%some_garbage = 2.0 

    this%basic_pointer = this%pointer_array(1) 
    this%pointer_array(1) = this%pointer_array(2) 
    this%pointer_array(2) = this%basic_pointer 

    this%basic_pointer = this%pointer_array(1) 
    hack => this%pointer_array(1) 
    hack = this%pointer_array(2) 
    hack => this%pointer_array(2) 
    hack = this%basic_pointer 
end subroutine 

end module 

當我試圖給索引指針數組即

this%pointer_array(1) = this%pointer_array(2) 
this%pointer_array(2) = this%basic_pointer 

我使用gfortran 4.8.4在Ubuntu。 我得到一個編譯錯誤:

Error: Variable must not be polymorphic in intrinsic assignment at (1) - check that there is a matching specific subroutine for '=' operator

分配到0D指針但是工作沒有怨言。 帶有「黑客」指針的部分顯示了一種可能的解決方法,以使其以醜陋的方式工作。

回答

0

編譯器抱怨它需要定義的賦值。你有一個,但它需要指針:

subroutine assign_base_class(result_object, input_object) 
    class(base_class), pointer, intent(out) :: result_object 
    class(base_class), pointer, intent(in) :: input_object 

(。這是沒有必要重複implicit none在所有模塊的程序我要說它是危害可讀性雜波)

和你的變量不是指針。 pointer_array(1)不是一個指針,即使pointer_array是一個指針。

一種解決方案是去除不需要的指針屬性:

subroutine assign_base_class(result_object, input_object) 
    class(base_class), intent(out) :: result_object 
    class(base_class), intent(in) :: input_object 
    result_object%some_garbage = input_object%some_garbage 
end subroutine 

這完全編譯。

如果你正在做指針賦值,那麼有pointer屬性是有意義的,但是就目前而言,在定義的賦值中沒有用處。