我以Metcalf等人的「Fortran 95/2003解釋」爲例,因爲m自己的代碼旨在實現相同的目的。如何爲擴展抽象類型的派生類型重載一個運算符?
type, abstract :: my_numeric_type
contains
private
procedure(op2), deferred :: add
generic, public :: operator(+) => add
end type
abstract interface
function op2(a,b) result (r)
import :: my_numeric_type
class(my_numeric type), intent(in) :: a,b
class(my_numeric type), allocatable :: r
end function op2
end interface
type, extends(my_numeric_type) :: my_integer
integer, private :: value
contains
procedure :: add => add_my_integer
end type
現在,我的問題是如何正確實現add_my_integer
函數。似乎我被迫將第一個參數強制轉換爲my_integer
,因爲它是一個類型綁定過程,但第二個參數必須是my_numeric_type
才能符合抽象接口。至於結果,我應該分配r
到my_integer
?這是我到目前爲止所做的,它編譯的,但它總是檢查類型似乎很奇怪,它會導致分段錯誤(也許是由於我的代碼有其他問題)。
function add_my_integer(a,b) result(r)
class(my_integer), intent(in) :: a
class(my_numeric_type), intent(in) :: b
class(my_numeric_type), allocatable :: r
allocate(my_integer :: r)
select type (b)
type is (my_integer)
r = a+b
end select
end function
你試過了哪個編譯器? – 2012-04-05 20:43:28
最新的ifort。 – tiam 2012-04-05 22:20:01