简体   繁体   English

带参数列表的Fortran类型定义

[英]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: 撇开MSB关于定义matrix要点的观察,如果您拥有最新的编译器,则可以像下面这样定义和声明参数化的 define -type

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; 并非所有广泛使用的Fortran编译器都实现2008标准的此功能;
  • the parameters m,n,k have a special attribute on their declaration, either len or kind ; 参数m,n,k在其声明中具有lenkind的特殊属性;
  • 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. 我包含了kind-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. 一个很好的例子,但是没有理由在实际代码中创建这个特定的用户定义类型,因为您可以获得具有lboundubound的矩阵的边界-您不必将它们存储在类型中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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