简体   繁体   中英

Fortran Type Definition with a parameter list

Please take a look at this code, why there are problems, how could I do this instead?

program main
type matrix(m,n)
    integer::m,n
    double precision,dimension(1:m,1:n)::value
end type matrix

type(matrix(2,3))::B
print*,"OK"
end program

Another question about this is: Can I have a type definition or module definition followed by a parameter list? Cause I saw this code from book , don't know why I cannot compile it.

Leaving aside MSB's observation about the point of defining matrix , and if you have a bang up-to-date compiler you could define and declare a parameterized defined-type rather like this:

type matrix(m,n,k)
    integer, len :: m,n
    integer, kind :: k
    real(kind=k), dimension(m,n) :: elements
end type matrix

...

type(matrix(4,3,selected_real_kind(0.0)) :: the_matrix

Note:

  • not all the widely-used Fortran compilers yet implement this feature of the 2008 standard;
  • the parameters m,n,k have a special attribute on their declaration, either len or kind ;
  • I've included the kind-type parameter just to show that it exists, it's not necessary to include it when you define a parameterised derived type.
program main

type matrix
    integer:: m, n
    double precision, dimension(:,:), allocatable :: value
end type matrix

type (matrix) :: mat1, mat2


mat1 % m = 2
mat1 % n = 3
allocate ( mat1 % value ( mat1 % m, mat1 % n ) )
mat1 % value = 5.0

mat2 % m = 4
mat2 % n = 5
allocate ( mat2 % value ( mat2 % m, mat2 % n ) )
mat2 % value = 6.0

print*,"OK"
end program

A good example but there is no reason to create this particular user-defined type in real code because you can obtained the bounds of a matrix with lbound and ubound -- you don't have to store them in a type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM