增加模块中的数组

时间:2019-07-01 15:42:44

标签: module fortran

我正在尝试在Fortran中编写一个小的模块/类。这个想法很基本:

  1. 使用专用的构造函数创建和初始化对象
  2. 在其中添加新元素

我已经写了Fortran,但是只有子例程,我将尝试使用面向对象的原理。目前,我有两个错误:

  1. 我构建的构造函数不起作用(似乎不接受我的输入参数)...
  2. add_bb过程不被接受。

MNWE:

   module test_mod
    implicit none

    type :: bb
       real :: item
       real,allocatable :: vect(:)
    end type bb

    interface bb
       procedure :: new_bb!,add_bb
    end interface bb

  contains

    type(bb) function new_bb(val,nbv)
      real, intent(in) :: val
      integer, intent(in) :: nbv
      integer :: ii

      new_bb%item=val
      allocate(new_bb%vect(nbv))

      print *,nbv
      do ii=1,nbv
        new_bb%vect(ii)=val
        print *,ii
      enddo

      print *,new_bb%vect
    end function new_bb

    type(bb)  function add_bb(it)
        real,intent(in) :: it
        integer :: sp
        real,allocatable :: tmp(:)

        sp=size(add_bb%vect)+1

        allocate(tmp(sp))
        tmp(1:sp-1) = add_bb%vect(1:sp-1)
        call move_alloc(tmp, add_bb%vect)
        add_bb%vect(sp)=it
    end function add_bb
  end module test_mod

  program test
    use test_mod
    implicit none

    type(bb) :: cc
    cc=bb(10,20)
    call cc%add_bb(10)

    print *,cc%item
    print *,cc%vect
    !
  end program test

1 个答案:

答案 0 :(得分:0)

我试图修复您代码中的错误,但是随着我的工作量越来越多,我发现了您代码中越来越多的基本缺陷。显然,这意味着您可能不太熟悉OOP,尤其是在Fortran中。因此,我建议您拿一本书,例如Metcalf等人的“ Modern Fortran Explained”。并学习这个话题。同时,这是您的代码的修订版,至少可以正常运行而不会出现语法错误:

   module test_mod
    implicit none

    type :: bb_type
       real :: item
       real, allocatable :: vect(:)
    contains
       procedure, pass :: add_bb
    end type bb_type

    interface bb_type
       procedure :: construct_bb
    end interface bb_type

  contains

    function construct_bb(val,nbv) result (bb)
      real, intent(in) :: val
      integer, intent(in) :: nbv
      type(bb_type) :: bb
      integer :: ii

      bb%item=val
      allocate(bb%vect(nbv))

      print *,nbv
      do ii=1,nbv
        bb%vect(ii)=val
        print *,ii
      enddo

      print *,bb%vect
    end function construct_bb

    subroutine add_bb(self,it)
        class(bb_type), intent(inout) :: self
        real,intent(in) :: it
        integer :: sp
        real, allocatable :: tmp(:)
        sp=size(self%vect)+1
        allocate(tmp(sp))
        !tmp(1:sp-1) = self%vect(1:sp-1)
        !call move_alloc(tmp, self%vect)
        !self%vect(sp)=it

end subroutine add_bb

  end module test_mod

  program test
    use test_mod
    implicit none

    type(bb_type) :: cc, dd
    cc=bb_type(10,[20])
    call dd%add_bb(10.0)

    print *,cc%item
    print *,cc%vect
    !
  end program test