Fortran/結構體
外觀
< Fortran
結構體、結構化型別或派生型別 (DT) 最初是在 Fortran 90 中引入的。[1] 結構體允許使用者建立包含多個不同變數的資料型別。
派生型別通常在模組中實現,以便使用者可以輕鬆地重複使用它們。 它們還可以包含型別繫結過程,這些過程旨在處理結構體。 引數 pass(name), nopass 指示物件是否應作為第一個引數傳遞。
類似於 character 資料型別,結構體可以透過兩種不同的引數型別進行引數化:kind, len。 kind 引數必須在編譯時已知(由常量組成),而 len 引數可以在執行時更改。
例如,我們可以定義一個新的結構體型別“Fruit”,它儲存一些基本的水果變數
type fruit
real :: diameter ! in mm
real :: length ! in mm
character :: colour
end type
我們可以宣告兩個“Fruit”變數,併為它們分配值
type (fruit) :: apple, banana
apple = fruit(50, 45, "red")
banana%diameter = 40
banana%length = 200
banana%colour = "yellow"
然後,我們可以在正常的 Fortran 操作中使用水果變數及其子值。
!> show the usage of type-bound procedures (pass/nopass arguments)
module test_m
implicit none
private
public test_type
type test_type
integer :: i
contains
procedure, nopass :: print_hello
procedure :: print_int
end type
contains
!> do not process type specific data => nopass
subroutine print_hello
print *, "hello"
end subroutine
!> process type specific data => first argument is "this" of type "class(test_type)"
!! use class and not type below !!!!
subroutine print_int(this)
class(test_type), intent(in) :: this
print *, "i", this%i
end subroutine
end module
program main
use test_m
implicit none
type (test_type) :: obj
obj%i = 1
call obj%print_hello
call obj%print_int
end program
! testing types with params: kind + len
program main
implicit none
type matrix(rows, cols, k)
integer, len :: rows, cols
integer, kind :: k = kind(0.0) ! optional/default value
real (kind=k), dimension(rows, cols) :: vals
end type
type (matrix(rows=3, cols=3)) :: my_obj
end program
- ↑ Fortran 90 概述 - Lahey 計算機系統