Oop 在Fortran中定义和调用构造函数

Oop 在Fortran中定义和调用构造函数,oop,types,interface,fortran,Oop,Types,Interface,Fortran,我不知道如何为一个类定义一个简单的构造函数。我要做的是在mytype中分配一个数组,然后在主程序中填充它 我所拥有的是: module types implicit none type mytype real, allocatable :: someArray(:) end type mytype interface module procedure :: init end interface contains

我不知道如何为一个类定义一个简单的构造函数。我要做的是在
mytype
中分配一个数组,然后在主程序中填充它

我所拥有的是:

module types
    implicit none

    type mytype
        real, allocatable :: someArray(:)
    end type mytype

    interface
        module procedure :: init
    end interface

contains
    subroutine init(this)
        class(mytype), intent(inout) :: this
        allocate( this%someArray(5) )
    end subroutine init
end module types

program test
  use types
  implicit none

  type(mytype) :: array

  call array%init
  do i=1, 5
    array%someArray(i) = real(i)
    print *, array%someArray(i)
  end do
end program test
当我编译时,我得到了错误

错误:(1)处的模块过程必须位于通用模块接口中

这是什么意思?如何定义通用模块接口


谢谢

用户提供的构造函数的语言模型是一个与类型具有相同标识符的泛型函数,它只返回该类型的对象。除了拥有与类型同名的泛型之外,这没有什么特别的

module types
  implicit none

  type mytype
    real, allocatable :: someArray(:)
  end type mytype

  interface mytype
    module procedure :: init
  end interface
  ! init would typically be private.
contains
  function init()
    type(mytype) :: this
    allocate( this%someArray(5) )
    ! Non-pointer function result must be defined.
    this%someArray = 0
  end function init
end module types

program test
  use types
  implicit none

  type(mytype) :: x

  x = mytype()

  do i=1, 5
    x%someArray(i) = real(i)
    print *, x%someArray(i)
  end do
end program test
(考虑到语言的其他方面,例如参数化类型、数组构造函数、自动分配,甚至内置结构构造函数的开箱即用功能,该示例有些毫无意义。)

来自编译器的错误消息可能意味着引用泛型接口,因为过程语句只允许在泛型的接口块中使用


特定类型绑定过程引用—语法为
object%binding
—通常在父类型具有具有特定签名的方法(一组伪参数,除了传递的参数)时使用,您希望在扩展中重写该方法,即调用具有相同签名的不同过程。构造函数不适合这种情况-通常需要传递给构造函数的信息(即调用的签名)是特定于类型的。

非常感谢您的回答!我显然不知道如何正确使用Fortran。您的提示为我打开了一个全新的世界,我将尝试在我的实现中使用其中的一些。请参阅Metcalf等人的“解释现代Fortran”。您将在本书中找到Fortran中OOP的详细解释以及示例。