一直以来都没有认真看过fortran90的文档,对于其中很多新特性都不清楚。以为fortran还能有什么oop? 不过下面这个例子倒是有点儿oop的味道。
Fortran 2003:完美还是虚幻?
例子是从这本书中找来的 Object-Oriented Programming via Fortran 90/95 at Amazon
! File: Fibonacci_Number.f90
!
! Fortran 90 OOP to print list of Fibonacci Numbers
!
module class_Fibonacci_Number
implicit none
public :: Print ! member access
private :: Add [...]
Fortran90的多态方法实现。from OOP via Fortran90/95
compute_area函数根据传入参数地不同而自动选择计算函数,并返回不同值。
excited, aha?
module class_Rectangle
implicit none
type Rectangle
real :: base, height
end type Rectangle
contains
function rectangle_area® result (area)
type(Rectangle), intent(in) :: r
real :: area
area = r%base * r%height
end function rectangle_area
end module [...]
在Fortran90中定义新的操作符,超载内部函数,固有操作符以及赋值号等。
下面这段代码定义了完整的有理数操作,其中超载’+‘、’*’ 操作符和’=‘赋值号,并定义了一个递归函数。保存为class_Rational.f90
module class_Rational
implicit none
! public everything but following private routines
private :: gcd, reduce
type Rational
private
integer :: num, den
end type Rational
interface assignment(=)
module procedure equal_Integer;
end interface
interface operator(+)
[...]