Skip to content
Fortran

モジュールと派生型

モジュールとOOPスタイルの型でコードを整理。

#module#type#oop

Code

fortran
module geometry
  implicit none
  private
  public :: point_type, distance

  type :: point_type
    real :: x = 0.0, y = 0.0
  contains
    procedure :: dist_to_origin
  end type

contains

  function distance(p1, p2) result(d)
    type(point_type), intent(in) :: p1, p2
    real :: d
    d = sqrt((p1%x - p2%x)**2 + (p1%y - p2%y)**2)
  end function

  function dist_to_origin(self) result(d)
    class(point_type), intent(in) :: self
    real :: d
    d = sqrt(self%x**2 + self%y**2)
  end function

end module

! Usage
program use_geom
  use geometry
  type(point_type) :: a, b
  a%x = 0; a%y = 0
  b%x = 3; b%y = 4
  print *, distance(a, b)    ! 5.0
  print *, b%dist_to_origin()! 5.0
end program