Fortran続きです。なんとFortranでも構造体が使えるんですね。ということで使ってみます。
typeとend typeの間にメンバ変数を定義します。
takk@deb9:~$ cat type.f90
program main
type test
integer i
character*10 name
end type test
type(test) a
a = test(1,'aaaa')
write(*,*) a%name
write(*,*) a%i
stop
end
takk@deb9:~$ gfortran type.f90
takk@deb9:~$ ./a.out
aaaa
1
takk@deb9:~$
構造体の変数名%メンバ名でアクセスできます。
当然ですが構造体は型なので、量産できます。
takk@deb9:~$ cat type.f90
program main
type test
integer i
character*10 name
end type test
type(test) a,b,c
a = test(1,'aaaa')
b = test(10,'bbbb')
c = test(100,'cccc')
write(*,*) a%name
write(*,*) a%i
write(*,*) b%name
write(*,*) b%i
write(*,*) c%name
write(*,*) c%i
stop
end
takk@deb9:~$ gfortran type.f90
takk@deb9:~$ ./a.out
aaaa
1
bbbb
10
cccc
100
takk@deb9:~$
構造体変数の定義は、途中で追加するのはエラーになるようです。
takk@deb9:~$ cat type2.f90
program main
type test
integer i
character*10 name
end type test
type(test) a
a = test(1,'aaaa')
write(*,*) a%name
write(*,*) a%i
type(test) b,c
b = test(10,'bbbb')
c = test(100,'cccc')
write(*,*) b%name
write(*,*) b%i
write(*,*) c%name
write(*,*) c%i
stop
end
takk@deb9:~$ gfortran type2.f90
type2.f90:13:22:
type(test) b,c
1
Error: Unexpected data declaration statement at (1)
type2.f90:17:21:
write(*,*) b%name
1
Error: Symbol ‘b’ at (1) has no IMPLICIT type
type2.f90:18:21:
write(*,*) b%i
1
Error: Symbol ‘b’ at (1) has no IMPLICIT type
type2.f90:19:21:
write(*,*) c%name
1
Error: Symbol ‘c’ at (1) has no IMPLICIT type
type2.f90:20:21:
write(*,*) c%i
1
Error: Symbol ‘c’ at (1) has no IMPLICIT type
type2.f90:14:12:
b = test(10,'bbbb')
1
Error: Can't convert TYPE(test) to REAL(4) at (1)
type2.f90:15:12:
c = test(100,'cccc')
1
Error: Can't convert TYPE(test) to REAL(4) at (1)
takk@deb9:~$
まあこれは構造体に限ったことではなく、変数の宣言が最初にないといけないのと同じですね。
takk@deb9:~$ cat var.f90
program main
integer i
i = 1
write(*,*) i
integer j
j = 2
write(*,*) j
stop
end
takk@deb9:~$ gfortran var.f90
var.f90:6:17:
integer j
1
Error: Unexpected data declaration statement at (1)
takk@deb9:~$



コメント