【发布时间】:2016-05-06 05:44:22
【问题描述】:
我试图理解抽象接口和“普通”接口之间的区别。是什么让接口抽象?什么时候需要?
假设下面的例子
module abstract_type_mod
implicit none
type, abstract :: abstract_t
contains
procedure(abstract_foo), pass, deferred :: Foo
end type
interface
subroutine abstract_foo ( this, a, b )
import :: abstract_t
implicit none
class(abstract_t), intent(in) :: this
real, intent(in) :: a
real, intent(out) :: b
end subroutine
end interface
end module
module concrete_type_mod
use abstract_type_mod
implicit none
type, extends ( abstract_t ) :: concrete_t
contains
procedure, pass :: Foo
end type
contains
subroutine Foo ( this, a, b )
implicit none
class(concrete_t), intent(in) :: this
real, intent(in) :: a
real, intent(out) :: b
b = 2 * a
end subroutine
end module
module ifaces_mod
implicit none
interface
subroutine foo_sub ( a, b )
implicit none
real, intent(in) :: a
real, intent(out) :: b
end subroutine
end interface
end module
module subs_mod
implicit none
contains
pure subroutine module_foo ( a, b )
implicit none
real, intent(in) :: a
real, intent(out) :: b
b = 2 * a
end subroutine
end module
program test
use ifaces_mod
use subs_mod
use concrete_type_mod
implicit none
type(concrete_t) :: concrete
procedure(foo_sub) :: external_sub
procedure(foo_sub), pointer :: foo_ptr
real :: b
foo_ptr => external_sub
call foo_ptr ( 0.0, b )
print*, b
foo_ptr => module_foo
call foo_ptr ( 1.0, b )
print*, b
call concrete%Foo ( 1.0, b )
print*, b
end program
pure subroutine external_sub ( a, b )
implicit none
real, intent(in) :: a
real, intent(out) :: b
b = a + 5
end subroutine
输出是
5.000000
2.000000
2.000000
我没有在这里使用抽象接口。至少我认为我没有?我已经这样做了一段时间,而且我从来没有在接口上使用过抽象的“限定符”。好像没有找到需要使用抽象接口的案例。
有人可以在这里启发我吗?
PS:编译器 Intel Visual Fortran Composer XE 2013 SP1 更新 3。
编辑:
在现代 Fortran 中引用 Metcalf、Reid 和 Cohen 的解释:
在 Fortran 95 中,使用 显式接口,需要使用接口块。这可以 对于单个过程,但对于声明多个过程有点冗长 具有相同接口的程序(除了程序 名称)。此外,在 Fortran 2003 中,有几种情况 这变得不可能(过程指针组件或 抽象类型的绑定过程)。
那么,我的编译器是否错误地接受了下面的代码以及上面的抽象类型的代码?
module ifaces_mod
implicit none
interface
subroutine foo_sub ( a, b )
implicit none
real, intent(in) :: a
real, intent(out) :: b
end subroutine
end interface
end module
module my_type_mod
use ifaces_mod
implicit none
type my_type_t
procedure(foo_sub), nopass, pointer :: Foo => null()
end type
end module
在这两种情况下,我会说我实际上已经声明了抽象接口,而没有使用 abstract 关键字。我认为我的困惑源于编译器接受这样的代码这一事实。
【问题讨论】: