Fortran 派生数据类型
Fortran 让您定义派生数据类型。派生数据类型也称为结构,它可以由不同类型的数据对象组成。
派生数据类型用于表示记录。例如,如果你想跟踪图书馆里的书,你可能想跟踪每本书的以下属性:
- Title
- Author
- Subject
- Book ID
定义派生数据类型
要定义派生数据类型,请使用类型和结束类型语句。type 语句定义了一个新的数据类型,程序有多个成员。类型语句的格式如下:
type type_namedeclarationsend type
以下是您声明 Book 结构的方式:
type Bookscharacter(len = 50) :: titlecharacter(len = 50) :: authorcharacter(len = 150) :: subjectinteger :: book_idend type Books
访问结构成员
派生数据类型的对象称为结构。
可以在类型声明语句中创建 Books 类型的结构,如下所示:
type(Books) :: book1
可以使用组件选择器字符(%)访问结构的组件:
book1%title = "C Programming"book1%author = "Nuha Ali"book1%subject = "C Programming Tutorial"book1%book_id = 6495407
请注意,% 符号前后没有空格。
实例
program deriveDataType!type declarationtype Bookscharacter(len = 50) :: titlecharacter(len = 50) :: authorcharacter(len = 150) :: subjectinteger :: book_idend type Books!declaring type variablestype(Books) :: book1type(Books) :: book2!accessing the components of the structurebook1%title = "C Programming"book1%author = "Nuha Ali"book1%subject = "C Programming Tutorial"book1%book_id = 6495407book2%title = "Telecom Billing"book2%author = "Zara Ali"book2%subject = "Telecom Billing Tutorial"book2%book_id = 6495700!display book infoPrint *, book1%titlePrint *, book1%authorPrint *, book1%subjectPrint *, book1%book_idPrint *, book2%titlePrint *, book2%authorPrint *, book2%subjectPrint *, book2%book_idend program deriveDataType
结果如下:
C ProgrammingNuha AliC Programming Tutorial6495407Telecom BillingZara AliTelecom Billing Tutorial6495700
结构数组
您还可以创建派生类型的数组:
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 declarationtype Bookscharacter(len = 50) :: titlecharacter(len = 50) :: authorcharacter(len = 150) :: subjectinteger :: book_idend type Books!declaring array of bookstype(Books), dimension(2) :: list!accessing the components of the structurelist(1)%title = "C Programming"list(1)%author = "Nuha Ali"list(1)%subject = "C Programming Tutorial"list(1)%book_id = 6495407list(2)%title = "Telecom Billing"list(2)%author = "Zara Ali"list(2)%subject = "Telecom Billing Tutorial"list(2)%book_id = 6495700!display book infoPrint *, list(1)%titlePrint *, list(1)%authorPrint *, list(1)%subjectPrint *, list(1)%book_idPrint *, list(1)%titlePrint *, list(2)%authorPrint *, list(2)%subjectPrint *, list(2)%book_idend program deriveDataType
结果如下:
C ProgrammingNuha AliC Programming Tutorial6495407C ProgrammingZara AliTelecom Billing Tutorial6495700