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
谢谢你,正是我所追求的! –