在Fortran中分配抽象类型的数组

时间:2019-03-21 13:23:31

标签: oop types fortran subroutine

基本上,我在基本模块中定义了抽象类包装类基类。强>。 abbstract类包含一个可分配数组和一个子例程。在构造函数中,我想分配此数组,但这不起作用。

分配确实适用于Base,但是我想那不是我想要的,因为子类对Base一无所知。我该如何分配?

这就是我所拥有的:

基本模块

module BaseClass

    implicit none

    ! ------------------------
    ! ABSTRACT CLASS
    ! ------------------------
    type, abstract :: AbsBaseHelper
        real, allocatable :: A(:)  !! <-- this makes problems
    contains
        procedure :: construct
        procedure(help_int), deferred :: help
    end type

    ! ------------------------
    ! WRAPPER CLASS
    ! ------------------------
    type :: BaseWrap
        integer :: cI
        class(AbsBaseHelper), pointer :: p
    contains
        procedure :: do_something
    end type

    ! ------------------------
    ! INTERFACE
    ! ------------------------
    interface
        subroutine help_int(this)
            import AbsBaseHelper
            implicit none
            class(AbsBaseHelper), intent(inout) :: this
        end subroutine help_int
    end interface

    ! ------------------------
    ! BASE CLASS
    ! ------------------------
    type(BaseWrap) :: Base(2)

contains

    ! ------------------------
    ! CONSTRUCTOR
    ! ------------------------
    subroutine construct(this, id)

        implicit none
        class(AbsBaseHelper), intent(in), target :: this
        integer, intent(in) :: id

        Base(id)%cI =  id
        ! allocate( this%A(2) )         !! <-- does not work because this is only intent(in)
        Base(id)%p  => this
        allocate( Base(id)%p%A(2) )     !! <-- does not work because it gives segmentation fault in 'help'

    end subroutine construct

    ! ------------------------
    ! THE MAIN SUBROUTINE
    ! ------------------------
    subroutine do_something(this)

        implicit none

        class(BaseWrap), intent(inout) :: this

        print*, "Base Index : ", this%cI
        call this%p%help()
        print*, "Result 1 : ", this%p%A(1)
        print*, "Result 2 : ", this%p%A(2)

    end subroutine do_something

end module BaseClass

子模块

module ChildClass1

    use BaseClass

    implicit none

    type, extends(AbsBaseHelper) :: Child1
    contains
        procedure :: help
    end type

contains

    subroutine help(this)
        implicit none
        class(Child1), intent(inout) :: this

        this%A(1) = 1   !! <-- produces segmentation fault
        this%A(2) = 2
    end subroutine

end module ChildClass1

程序

program test

    use BaseClass

    implicit none

    call init
    call Base(1)%do_something()

contains

    ! ------------------------
    ! INITIALIZE
    ! ------------------------
    subroutine init

        use ChildClass1

        implicit none

        type(Child1), target :: c1

        call c1%construct(1)

    end subroutine init

end program test

0 个答案:

没有答案