我想重載一個我想用於多態指針的類型的賦值。我不知道指針在運行時持有的實際子類型。 但下面的示例代碼重新奇怪編譯器錯誤,我得到:帶指針的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指針但是工作沒有怨言。 帶有「黑客」指針的部分顯示了一種可能的解決方法,以使其以醜陋的方式工作。