fortran operator overloading (=)

柔情痞子 提交于 2019-12-06 00:29:46

For defined assignment operator(=) is not correct, but assignment(=) is: see Fortran 2008 12.4.3.4.3. So you instead want the two lumps

public :: assignment (=)

and

interface assignment (=)
  module procedure vectorAssign
end interface

Note that the correct way to define the assignment is by the subroutine as you have it (although the assignee could have intent(out) instead of intent(inout)).

= is not an operator, it is an assignment in Fortran and they are very different beasts.

To the classical possibility found in Fortran 90 and explained well in other answers, Fortran 2003 added a better possibility to bind the overloaded operators and assignments with the derived type.

This way you are sure you will not import the type without the assignment (beware of public and private statement in this case!). It can have very unpleasant consequences and can be hard to debug:

type vectorField
  integer,dimension(3) :: sx,sy,sz
  real(dpn),dimension(:,:,:),allocatable :: x,y,z
contains
  procedure :: assignVector
  generic :: assignment(=) => assignVector
end type

This way you do not have to be that careful to not forget the public :: assignment (=)

Yes, you can overload the assignment operator. The syntax and requirements are different for the assignment operator than for other operators because the semantics are fundamentally different: all other operators compute a new value based on one or two arguments, without changing the arguments, whereas assignment changes the value of the left-hand argument.

In your case, I think it should look like this:

module vectorField_mod

! ...

  interface assignment (=)
    module procedure vectorAssign
  end interface

contains

  ! ...

  subroutine vectorAssign(f,g)
    implicit none
    type(vectorField),intent(out) :: f
    real(kind = dpn), intent(in) :: g
    f%x = g
    f%y = g
    f%z = g
  end subroutine vectorAssign

end module vectorField_mod
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!