本帖最后由 weixing1531 于 2019-6-27 20:24 编辑  
 
方法1:传统方法 
模块中 
[Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode type,public :: rational !分数类
    private
    integer :: num    ! 分子
    integer :: denom  ! 分母
contains
    private
    procedure,pass(this),public :: rational=>new
end type rational
...
subroutine new(this,nn,dd) !构造函数
    class(rational), intent(out) :: this
    integer, intent(in) :: nn,dd
    ...
end subroutine new 
主程序中 
[Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode type(rational)::a
call a%rational(1,2)  
方法2:GitHub上大牛们喜欢用 
模块中 
[Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode type,public :: rational !分数类
    private
    integer :: num    ! 分子
    integer :: denom  ! 分母
contains
    private
    ...
end type rational
interface rational
    procedure :: new
end interface
...
function new(nn,dd) result(rs)
    integer, intent(in) :: nn,dd
    type(rational)::rs
    ...
end function new 
主程序中 
[Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode type(rational)::a
a=rational(1,2)  
两种构造方法有什么区别呢? 
个人理解 
方法1:构造方法是子例程,属于实例方法,子类可以继承或重写父类的构造方法,子类重写构造方法时可用call this%父类名%构造方法名()来节省对象初始化的代码量 
方法2:构造方法是函数,属于模块方法(实用方法),采用接口名与类名重名的方式,在属性私有前提下实现了结构构造器,子类不可以继承父类的构造函数,需要在子类所在模块中手动写构造函数(不能与父类构造函数重名) 
 
 
 
 
 |