5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Fortran の単項・二項演算子のオーバーロード

Last updated at Posted at 2018-03-08

Fortran での operator overload

Fortran90 で、単項演算子および二項演算子に対して、演算子オーバーロードが定義できるようになりました。組み込み型の単項演算子・二項演算子に対しては、組み込み型ですでに定義されている被演算子の型とダブらない必要があります。それは区別がつかなくなるためだと思います。

では、どのような組み込み型演算子に対してオーバーロードできるのか探してみました。素朴に考えて、正負の符号を与える単項演算子と加減乗除の二項演算子が思いつきます。このほかにべき乗の ** や、文字列結合の // も二項演算子としてオーバーロードできます。また、≧,≦,>,<,==,/= のような比較演算子や論理演算の二項演算子もオーバーロードできます。

単項演算子には、他に論理型を否定する .not. 演算子がありますが、前後に . の付いた演算子は、自由に定義できるので、それほど意味も無かろうかと思います。

演算子にはまだ見落としがあるかもしれません。
なおこれに加えるに、代入演算子 = もオーバーロードできます。

ソース・プログラム

module m_mod
  implicit none
! binary / dyadic  
  interface  operator (>=) !.ge.
    module procedure op2
  end interface
  interface  operator (>) !.gt.
    module procedure op2
  end interface
  interface  operator (<=) !.le.
    module procedure op2
  end interface
  interface  operator (<) !.lt.
    module procedure op2
  end interface
    interface  operator (==) !.eq.
    module procedure op2
  end interface
  interface  operator (/=) !.ne.
    module procedure op2
  end interface
  interface  operator (//) 
    module procedure op2
  end interface
  interface  operator (**)
    module procedure op2
  end interface
  interface  operator (.and.) !.or. .eqv. .neqv.
    module procedure op2
  end interface
 
! unary / monadic  
  interface  operator (.not.)
    module procedure op1
  end interface
  interface  operator (+)
    module procedure op1
  end interface
  interface  operator (-)
    module procedure op1
  end interface
contains  
  pure integer function op2(c1, i)
    character, intent(in) :: c1
    integer  , intent(in) :: i
    op2 = iachar(c1) + i
  end function op2    

  pure integer function op1(c1)
    character, intent(in) :: c1
    op1 = iachar(c1) 
  end function op1    
end module m_mod

program hello
  use m_mod
  implicit none
!  print *, 'c' >= 5, .not.'a'
  print *, .not. 'a'
  print *, +'b'
  print *, -'c'
end program hello

実行結果

          97
          98
          99
続行するには何かキーを押してください . . .
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?