[Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode
Module VectClass
  TYPE :: Vect
    Real(8) ,Private :: x
    Real(8) ,Private :: y
    Real(8) ,Private :: z 
  Contains
    Procedure :: set
    Procedure,pass(ThisVect),Private :: VectMulScal_Fn , ScalMulVect_Fn , VectMulVect_Fn
    Generic, Public :: operator (*) => VectMulScal_Fn , ScalMulVect_Fn , VectMulVect_Fn
    Procedure :: writef
    Generic :: write(formatted) => writef
  End TYPE
contains
  Subroutine set(this,x,y,z)
    class(Vect) :: this
    Real(8), Intent(IN) :: x , y , z
    this%x = x ; this%y = y ; this%z = z
  End Subroutine set
  Subroutine writef(this, unit, iotype, v_list, iostat, iomsg)
    class(vect), intent(in) :: this
    integer, intent(in) :: unit
    character (len=*), intent(in) :: iotype
    integer, intent(in) :: v_list(:)
    integer, intent(out) :: iostat
    character (len=*), intent(inout) :: iomsg
    write(unit , iotype(3:) , iostat=iostat, iomsg=iomsg) this%x , this%y , this%z
   End Subroutine writef
  Type(Vect) Function ScalMulVect_Fn(ThisVect,Scal) result( y )
    real(8) , Intent(IN) :: Scal
    class(Vect) , Intent(IN) :: ThisVect
    y = Vect( ThisVect%x * Scal , ThisVect%y * Scal , ThisVect%z * Scal )
  End Function ScalMulVect_Fn
  Type(Vect) Function VectMulScal_Fn(Scal,ThisVect) result( y )
    real(8) , Intent(IN) :: Scal
    class(Vect) , Intent(IN) :: ThisVect
    y = ThisVect * Scal
  End Function VectMulScal_Fn
  Type(Vect) Function VectMulVect_Fn(ovect,ThisVect) result( y )
    class(Vect) , Intent(IN) :: ovect , ThisVect
    y = Vect( ThisVect%x * ovect%x , ThisVect%y * ovect%y , ThisVect%z * ovect%z )
  End Function VectMulVect_Fn
End Module VectClass
Program Main
  use VectClass
  type(Vect) :: a , b , c
  call a%set(1.d0,2.d0,3.d0)
  b = a * 3.0d0
  write(*,'(a,dt"(3f6.2)")') "b=" , 3.0d0*b
  c = a * ( 3.d0 * b )
  write(*,'(dt"(3f6.2)")') c
End Program Main