3
類
假設我有這個簡單的類的類型綁定寫語句輸出:如何實現在Fortran派生型或
Module Foo
...
character(len=3), parameter :: describe_Foo=(/'BAR', 'BED', 'BOD'/)
...
type :: A
real :: value
integer :: descriptor
contains
procedure :: getter
procedure :: setter
...
end type A
contains
function writetype(self,...)
...
write(writetype,*) self%value, describe_foo(self%descriptor)
end function writetype
...
end module Foo
我如何定義它的界面來「寫」,讓每一次這個type傳遞給write語句,它輸出由類方法writetype定義的字符串。
換句話說,用python的說法,我可以實現__str __()方法的等價物嗎?
我發現了誘人的花絮,暗示這是可能的,請參閱User-defined derived-type Input/Output procedures (Fortran 2003)和User-defined derived-type Input/Output procedure interfaces (Fortran 2003)。這些文檔提供了足夠的信息來編寫我需要的方法,但是我仍然不清楚如何定義接口或過程規範,以便發生我想要的行爲。
應用示例:
program test
...
type(A) :: bartype, bedtype
...
bartype=A(120.0,1)
bedtype=A(102.0,2)
write(*,*) bartype,bedtype
end program test
希望的輸出:
>test.exe
120.0000 BAR
102.0000 BED
謝謝你,正是我所追求的! –