Fortran:派生数据类型

声明:本博文翻译自:https://www.tutorialspoint.com/fortran/fortran_derived_data_types.htm

1. 定义派生数据类型
使用type ...end type语句块进行派生数据类型的声明。
其语法结构如下:
type type_name      
   declarations
end type 
这里给出一个关于书本结构的派生数据类型定义
type Books
   character(len = 50) :: title
   character(len = 50) :: author
   character(len = 150) :: subject
   integer :: book_id
end type Books

2. 访问派生数据类型成员
派生数据类型的对象被称为结构
可以像这样在类型声明语句中创建类型图书的结构
type(Books) :: book1
可以使用%字符访问结构的成员
book1%title = "C Programming"
book1%author = "Nuha Ali"
book1%subject = "C Programming Tutorial"
book1%book_id = 6495407

3. 示例代码
Program deriveDataType

  !type declaration
  type Books
     character(len = 50) :: title
     character(len = 50) :: author
     character(len = 150) :: subject
     integer :: book_id
  end type Books

  !declaring type variables
  type(Books) :: book1 
  type(Books) :: book2 

  !accessing the components of the structure

  book1%title = "C Programming"
  book1%author = "Nuha Ali"
  book1%subject = "C Programming Tutorial"
  book1%book_id = 6495407 

  book2%title = "Telecom Billing"
  book2%author = "Zara Ali"
  book2%subject = "Telecom Billing Tutorial"
  book2%book_id = 6495700

  !display book info

  Print *, book1%title 
  Print *, book1%author 
  Print *, book1%subject 
  Print *, book1%book_id  

  Print *, book2%title 
  Print *, book2%author 
  Print *, book2%subject 
  Print *, book2%book_id  

End program deriveDataType
运行结果如下:
 C Programming
 Nuha Ali
 C Programming Tutorial

     6495407
 Telecom Billing
 Zara Ali
 Telecom Billing Tutorial

     6495700

接下来使用派生数据数组对上面代码进行改写:
Program deriveDataType

  !type declaration
  type Books
     character(len = 50) :: title
     character(len = 50) :: author
     character(len = 150) :: subject
     integer :: book_id
  end type Books

  !declaring array of books
  type(Books), dimension(2) :: list 

  !accessing the components of the structure

  list(1)%title = "C Programming"
  list(1)%author = "Nuha Ali"
  list(1)%subject = "C Programming Tutorial"
  list(1)%book_id = 6495407 

  list(2)%title = "Telecom Billing"
  list(2)%author = "Zara Ali"
  list(2)%subject = "Telecom Billing Tutorial"
  list(2)%book_id = 6495700

  !display book info

  Print *, list(1)%title 
  Print *, list(1)%author 
  Print *, list(1)%subject 
  Print *, list(1)%book_id  

  Print *, list(1)%title 
  Print *, list(2)%author 
  Print *, list(2)%subject 
  Print *, list(2)%book_id  

End program deriveDataType
运行结果如下:
 C Programming
 Nuha Ali
 C Programming Tutorial

     6495407
 C Programming
 Zara Ali
 Telecom Billing Tutorial

     6495700
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值