Derived 数据类型
优质
小牛编辑
134浏览
2023-12-01
Fortran允许您定义派生数据类型。 派生数据类型也称为结构,它可以由不同类型的数据对象组成。
派生数据类型用于表示记录。 例如,您想要在图书馆中跟踪您的图书,您可能希望跟踪每本图书的以下属性 -
- Title
- Author
- Subject
- Book ID
定义派生数据类型
要定义派生数据type ,请使用类型和end type语句。 。 type语句定义一个新的数据类型,为您的程序提供多个成员。 类型语句的格式是这样的 -
type type_name
declarations
end type
以下是您声明Book结构的方式 -
type Books
character(len = 50) :: title
character(len = 50) :: author
character(len = 150) :: subject
integer :: book_id
end type Books
访问结构成员 (Accessing Structure Members)
派生数据类型的对象称为结构。
可以在类型声明语句中创建Books类型的结构,如 -
type(Books) :: book1
可以使用组件选择器字符(%)访问结构的组件 -
book1%title = "C Programming"
book1%author = "Nuha Ali"
book1%subject = "C Programming Tutorial"
book1%book_id = 6495407
Note that there are no spaces before and after the % symbol.
例子 (Example)
以下程序说明了上述概念 -
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
结构数组
您还可以创建派生类型的数组 -
type(Books), dimension(2) :: list
阵列的各个元素可以访问为 -
list(1)%title = "C Programming"
list(1)%author = "Nuha Ali"
list(1)%subject = "C Programming Tutorial"
list(1)%book_id = 6495407
以下计划说明了这一概念 -
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