我正在尝试在Fortran中编写一个小的模块/类。这个想法很基本:
我已经写了Fortran,但是只有子例程,我将尝试使用面向对象的原理。目前,我有两个错误:
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
答案 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