可分配数组作为派生类型的一部分

时间:2014-02-14 23:30:52

标签: fortran

使用英特尔Visual Fortran XE 2013(启用了2003语法)和Visual Studio 2012

我有一个派生类型,可分配数组作为组件。当我尝试分配数组或将可分配数组设置为等于数组时,它似乎不起作用。没有错误,但似乎没有值。

下面是一个应该说明问题的例子。

Type myType
    integer :: var1, var2
    real*8,dimension(:), allocatable :: listOfReals
    integer, dimension(:), allocatable :: listOfInts
end Type myType

function setTheValues(someParams) result(typeA)

    type(params_T), intent(in) :: someParams
    type(myType_T) :: typeA

    type(lists_t)  :: lists 

    typeA%var1 = 1
    typeA%var2 = 2
    !where getList is a function that returns an 
    !object with an array of real numbers and an array of ints
    lists = getLists(someParams)
    typeA%listOfReals = lists%reals
    typeA%listOfInts = lists%ints

end function setTheValues 

这不起作用。也没有:

function setTheValues(someParams) result(typeA)

    type(params_T), intent(in) :: someParams
    type(myType_T) :: typeA

    type(lists_t)  :: lists


    typeA%var1 = 1
    typeA%var2 = 2

    allocate(typeA%listOfReals(12))
    allocate(typeA%listOfInts(12))

    !where getList is a function that returns an 
    !derivedtype with an array of real numbers and an array of ints both of size 12
    lists = getLists(someParams)
    typeA%listOfReals = lists%reals
    typeA%listOfInts = lists%ints

end function setTheValues

我要么得到的东西说价值不存在,它不会显示任何值,或者它给了我一个数组,其中包含看似是带有错误数据的巨大随机索引值。

非常感谢任何帮助。

编辑:我在代码的其他部分做了类似的事情,即使调试器似乎仍然无法正确显示值,它们似乎也正常工作。

1 个答案:

答案 0 :(得分:1)

module MyStuff

use, intrinsic :: ISO_FORTRAN_ENV

implicit none

type myType
    integer :: var1, var2
    real (real64), dimension(:), allocatable :: listOfReals
end Type myType

contains

function setTheValues () result(typeA)
   type (myType) :: typeA

   typeA % var1 = 1
   typeA % var2 = 2

   allocate ( typeA % listOfReals(12))
   typeA % listOfReals = getList()

end function setTheValues

function getList ()

   real (real64), dimension (12) :: getList
   getList = [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0 ]

end function getList

end module MyStuff


program MyProg

use MyStuff

implicit none

type (myType) :: myType1

myType1 = setTheValues ()

write (*, *) myType1 % var1, myType1 % var2
write (*, *) myType1 % ListofReals

end program MyProg