使用类型过程获取派生类型的数组分的单个值

时间:2018-04-26 11:03:06

标签: fortran gfortran

我的IDE是Code :: Blocks 17.2,带有编译器GFortran 6.3.1

代码是:

MODULE CLASS_BRANCHES

IMPLICIT NONE

  TYPE , PUBLIC :: TS_SHIR

    PRIVATE

      COMPLEX , ALLOCATABLE :: Y_BRA (:)

    CONTAINS

      PROCEDURE , PUBLIC :: CALCULATION_TS_SHIR => CALCULATION_DATA_TS_SHIR
!      PROCEDURE , PUBLIC :: TAKE_Y_BRA => TAKE_DATA_Y_BRA

  END TYPE TS_SHIR

  PRIVATE :: CALCULATION_DATA_TS_SHIR
!  PRIVATE :: TAKE_DATA_Y_BRA

CONTAINS

SUBROUTINE CALCULATION_DATA_TS_SHIR( THIS , N_BRA )

  IMPLICIT NONE

  CLASS ( TS_SHIR ) , INTENT( INOUT ) :: THIS
  INTEGER , INTENT ( IN ) :: N_BRA
  INTEGER :: I , ALLOC_ERR

  IF ( .NOT. ALLOCATED ( THIS%Y_BRA ) ) ALLOCATE ( THIS%Y_BRA ( N_BRA ) , STAT = ALLOC_ERR )

  IF ( ALLOC_ERR .NE. 0 ) STOP ("MEMORY ALLOCATION PROBLEM - THIS%Y_BRA!")

  DO I = 1 , N_BRA

     THIS%Y_BRA(I) = CMPLX ( 11 + I , 12 + I )

  END DO

RETURN
END SUBROUTINE CALCULATION_DATA_TS_SHIR

!FUNCTION TAKE_DATA_Y_BRA ( THIS ) RESULT ( DATA_Y_BR )
!
!    IMPLICIT NONE
!
!    CLASS ( TS_SHIR ) :: THIS
!    COMPLEX :: DATA_Y_BR
!
!    DATA_Y_BR = THIS%Y_BRA
!
!RETURN
!END FUNCTION TAKE_DATA_Y_BRA

END MODULE CLASS_BRANCHES

PROGRAM TYPE_ALLOCATABLE_ARRAY

USE , NON_INTRINSIC :: CLASS_BRANCHES

IMPLICIT NONE

INTEGER :: I , J
INTEGER , PARAMETER :: N_BRANCHES = 5 , N_CALCULATIONS = 6
CHARACTER( 250 ) , DIMENSION ( N_CALCULATIONS ) :: UN_NAME
CHARACTER(*) , PARAMETER :: UN_FMT = '("OUTPUT_",I2.2,".TXT")'  

CLASS ( TS_SHIR ) , POINTER :: P_BRA
TYPE ( TS_SHIR ) , DIMENSION ( N_CALCULATIONS ) , TARGET :: BRANCHES  

LOOP_00: DO I = 1 , N_CALCULATIONS

            P_BRA => BRANCHES(I)

            CALL P_BRA%CALCULATION_TS_SHIR( N_BRANCHES )

            WRITE( UN_NAME(I) , UN_FMT ) I

            OPEN ( 15 , FILE = UN_NAME(I) , STATUS = 'UNKNOWN' , ACTION = 'WRITE' )

              DO J = 1 , N_BRANCHES

                 WRITE( 15 , * ) J ! HOW TO WRITE VALUES OF Y_GRA( N_BRA ) WITH MEMBER FUNCTION OF TYPE TS_SHIR???

              END DO

            CLOSE ( 15 , STATUS = 'KEEP')

         END DO LOOP_00

END PROGRAM TYPE_ALLOCATABLE_ARRAY

我是Fortran中面向对象编程的新手,所以我需要一个关于通过公共过程Type获取TAKE_Y_BRA私有成员(可分配数组)的值的解释。我对函数TAKE_Y_BRA的主体发表评论,因为我得到了他的信息: Incompatible ranks 0 and 1 in assignment位于此命令的行: DATA_Y_BR = THIS%Y_BRA 有没有解决方案,或者我有一个完全错误的方法用于派生类型的这种计算?

1 个答案:

答案 0 :(得分:0)

返回整个数组

FUNCTION TAKE_DATA_Y_BRA ( THIS ) RESULT ( DATA_Y_BR )
   CLASS ( TS_SHIR ) :: THIS
   COMPLEX :: DATA_Y_BR(SIZE(THIS%Y_BRA))

   DATA_Y_BR = THIS%Y_BRA
END FUNCTION TAKE_DATA_Y_BRA

或者在索引J

返回一个元素
FUNCTION TAKE_DATA_Y_BRA_J ( THIS, J ) RESULT ( DATA_Y_BR )
   CLASS ( TS_SHIR ) :: THIS
   INTEGER, INTENT(IN) :: J
   COMPLEX :: DATA_Y_BR

   DATA_Y_BR = THIS%Y_BRA(J)
END FUNCTION TAKE_DATA_Y_BRA_J

请注意,您并非真正需要implicit nonereturn。简明扼要。你的代码很难读懂!使用小型大写字母以提高可读性。