[Fortran] 纯文本查看 复制代码
module super_class !父类
implicit none
private
type,public::point
real::x=0.0
real::y=0.0
procedure(sub),pointer::p=>null() !过程指针作为成员变量
contains
procedure,pass::point_new !父类构造函数
procedure,pass::printSum !打印成员变量之和
end type point
abstract interface !抽象接口
subroutine sub(me,x,f)
import::point !导入宿主定义
class(point),intent(inout)::me
real,dimension(:), intent(in)::x
real,intent(out) ::f
end subroutine sub
end interface
contains
subroutine point_new(me,x,y) !父类构造函数
class(point),intent(inout)::me
real,intent(in)::x
real,intent(in)::y
me%x=x
me%y=y
end subroutine point_new
subroutine printSum(me,pp)
class(point),intent(inout)::me
procedure(sub)::pp !任何与子例程sub形参列表相同的子例程都能传入
real::f
me%p=>pp !过程指针确定指向
call me%p([me%x,me%y],f) !相当于call me%pp()
write(*,*)'父类sum=',f
end subroutine printSum
end module super_class
module sub_class !子类
use super_class
implicit none
private
type,public,extends(point)::point3d
real::z=0.0
contains
procedure,pass::point3d_new !子类构造函数
procedure,pass::printSum !打印成员变量之和 子类重写覆盖
end type point3d
abstract interface !抽象接口
subroutine sub(me,x,f)
import::point !导入宿主定义
class(point),intent(inout)::me
real,dimension(:), intent(in)::x
real,intent(out) ::f
end subroutine sub
end interface
contains
subroutine point3d_new(me,x,y,z) !子类构造函数
class(point3d),intent(inout)::me
real,intent(in)::x
real,intent(in)::y
real,intent(in)::z
call me%point%point_new(x,y) !调用父类的构造函数
me%z=z
end subroutine point3d_new
subroutine printSum(me,pp) !子类重写覆盖
class(point3d),intent(inout)::me
procedure(sub)::pp !任何与子例程sub形参列表相同的子例程都能传入
real::f
me%p=>pp !过程指针确定指向
call me%p([me%x,me%y,me%z],f) !相当于call me%pp()
write(*,*)'子类sum=',f
end subroutine printSum
end module sub_class
program main !主程序
use super_class
use sub_class
implicit none
type(point)::a
type(point3d)::b
call a%point_new(1.0,1.0)
call a%printSum(sss)
call b%point3d_new(2.0,2.0,2.0)
call b%printSum(sss)
contains
subroutine sss(me,x,f) !抽象接口具体实现
class(point),intent(inout)::me
real,dimension(:), intent(in)::x
real,intent(out) ::f
f=sum(x)
end subroutine sss
end program main