Operator Overloading and Arrays

0 views
Skip to first unread message

PGK

unread,
Jul 12, 2009, 6:41:31 PM7/12/09
to gg95
Hi all,

Can I overload an operator (+) for an array of derived type elements?
With code like the following, I end up with an error: Operands of
binary numeric operator '+' at (1) are TYPE(vec3)/TYPE(vec3)

Cheers,
Graham

type, public :: vec3
real(kind=k), dimension(3) :: es
end type vec3

function addvec3(a,b) result(c)
type(vec3), intent(in) :: a, b
type(vec3) :: c
c%es = a%es + b%es
end function addvec3

...

type(vec3), dimension(numelems) :: a, b

do i = 1, numelems ! Works fine
a(i) = a(i) + b(i)
enddo

a = a + b ! Gives the error I mentioned

jfh

unread,
Jul 12, 2009, 10:30:08 PM7/12/09
to gg95
Various things were left out, such as telling the compiler that
addvec3 was overloading the operator +. I think that has to be done
in a module, so here is an example as close as possible to the
original that will compile, run, and print a result showing that it
works:

module vec3stuff
integer,parameter:: k=selected_real_kind(14) ! double precision
type, public :: vec3
real(kind=k), dimension(3) :: es
end type vec3
interface operator (+)
module procedure addvec3
end interface
contains
elemental function addvec3(a,b) result(c)
type(vec3), intent(in) :: a, b
type(vec3) :: c
c%es = a%es + b%es
end function addvec3
end module vec3stuff

program usingvec3
use vec3stuff
integer,parameter:: numelems = 1
type(vec3), dimension(numelems) :: a, b
a(1)%es = (/ 1._k, 2._k, 1/9._k /)
b = a
print *,'a=',a
do i = 1, numelems ! Works fine
a(i) = a(i) + b(i)
enddo
print *,'a=',a
a = a + b ! No longer gives the error
print *,'a=',a
end program usingvec3

John Harper

Beliavsky

unread,
Jul 13, 2009, 7:58:45 AM7/13/09
to gg95
You declared addvec3 as taking scalar arguments. To make it accept
arrays, you need to declare it ELEMENTAL.


PGK

unread,
Jul 13, 2009, 12:33:17 PM7/13/09
to gg95
Thankyou both.
Reply all
Reply to author
Forward
0 new messages