Fortran導出數據類型
Fortran語言可以定義導出的數據類型。導出的數據類型也被稱為一個結構,它可以包含不同類型的數據對象。
導出的數據類型被用來代表一個記錄。例如要跟蹤在圖書館的書,可能希望跟蹤的每本書有如下屬性:
- 標題- Title
- 作者 - Author
- 科目 - Subject
- 編號 - Book ID
定義一個導出的數據類型
定義一個派生數據類型,類型和端類型的語句被使用。類型語句定義了一個新的數據類型,項目不止一個成員。類型聲明的格式是這樣的:
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
訪問結構成員
一個派生數據類型的對象被稱為結構
類型書籍(Books) 的結構像一個類型聲明語句創建如下:
type(Books) :: book1
結構的組成部分可以使用該組件選擇字符(%)進行訪問 :
book1%title = "C Programming" book1%author = "Nuha Ali" book1%subject = "C Programming Tutorial" book1%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 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