Fortran Coder

查看: 7250|回复: 7
打印 上一主题 下一主题

[面向对象] 抽象类中的过程

[复制链接]

1963

帖子

12

主题

5

精华

论坛跑堂

臭石头雪球

F 币
1357 元
贡献
574 点

美女勋章热心勋章星光勋章新人勋章贡献勋章管理勋章帅哥勋章爱心勋章规矩勋章元老勋章水王勋章

楼主
发表于 2018-11-22 17:20:43 | 显示全部楼层
定义了一个deferred的过程之后,父类可以调用这个过程。这样形成统一的接口。
其他使用 class(父类) 为参数的过程,也可以调用这个过程,而不需要判断对象属于哪个子类。(因为每个子类都有一个相同接口的函数)

给你一个例子

[Fortran] 纯文本查看 复制代码
Module Abst  Implicit None 
  Type , abstract , public :: T_People
    character(len=30) :: name
  contains
    Procedure(itf_intro), deferred :: introduction
    Procedure :: whoami
  End Type T_People
  interface
    Subroutine itf_intro(this)
      import
      class(T_People):: this
    End Subroutine itf_intro
  end interface

contains

  Subroutine whoami( this )
    class(T_People) :: this
    write(*,*) "Who am I ?"
    call this%introduction()
  End Subroutine whoami
End Module Abst

Module People
  use Abst
  Implicit None
  Type , extends(T_People), public :: T_Chinese    
  contains
    Procedure :: introduction => intro_chinese
  End Type T_Chinese
  Type , extends(T_People), public :: T_English
  contains
    Procedure :: introduction => intro_english
  End Type T_English

contains
  Subroutine intro_chinese(this)
    class(T_Chinese):: this
    write(*,*) "我的名字叫:" , this%name
  End Subroutine intro_chinese
  Subroutine intro_english(this)
    class(T_English):: this
    write(*,*) "My name is:" , this%name
  End Subroutine intro_english
End Module People

Program Main
  use People
  Implicit None
  type(T_Chinese) :: xiaoming = T_Chinese("小明")
  type(T_English) :: John = T_English("John")
  call xiaoming%introduction()
  call some(xiaoming)
  call some(John)
contains

  Subroutine some(someone)
    class(T_People) :: someone
    call someone%whoami()
  End Subroutine some
End Program Main

1963

帖子

12

主题

5

精华

论坛跑堂

臭石头雪球

F 币
1357 元
贡献
574 点

美女勋章热心勋章星光勋章新人勋章贡献勋章管理勋章帅哥勋章爱心勋章规矩勋章元老勋章水王勋章

沙发
发表于 2018-11-22 21:00:34 | 显示全部楼层
多试试,朋友。

deferred 是一个语法规范,并没有规定“什么情况下才能用”,更没有“只有.... 才使用”这种说法。

每个人都有自己的需求,我并没有那么广袤的了解过所有的需求,也很少考虑“在几种情况下,才会使用”这类问题。
您需要登录后才可以回帖 登录 | 极速注册

本版积分规则

捐赠本站|Archiver|关于我们 About Us|小黑屋|Fcode ( 京ICP备18005632-2号 )

GMT+8, 2024-5-2 14:17

Powered by Tencent X3.4

© 2013-2024 Tencent

快速回复 返回顶部 返回列表