1

我想在子例程(或函数)中计算派生数据类型。我将如何在子例程参数中引用变量?

到目前为止,我可以通过引用整个对象,然后在子例程中引用变量来实现我的目标。有没有办法在子例程参数中只引用变量 myObj%var ?

PROGRAM test

    TYPE obj
        INTEGER :: var
    END TYPE obj

    TYPE (obj) :: myObj
    CALL set(myObj)
    PRINT*, myObj%var

        CONTAINS

    SUBROUTINE set(myObj)
        TYPE (obj) :: myObj
        myObj%var = 5
    END SUBROUTINE set

END PROGRAM test
4

2 回答 2

2

If you only have an F95 compiler without all the 2003/2008 bits, this is how it can be done.

MODULE ObjMod
  IMPLICIT NONE

  TYPE ObjType
     INTEGER, PRIVATE :: var
  END TYPE ObjType

CONTAINS

  SUBROUTINE ObjCreate(this)
     TYPE(ObjType), POINTER :: this
     allocate(this)
  END SUBROUTINE ObjCreate

  SUBROUTINE ObjDelete(this)
     TYPE(ObjType), POINTER :: this
     deallocate (this)
  END SUBROUTINE ObjDelete

  SUBROUTINE ObjSet(this, value)
     TYPE(ObjType), INTENT(inout) :: this
     INTEGER, INTENT(in) :: value
     this%var = value
  END SUBROUTINE ObjSet

 INTEGER FUNCTION ObjGet(this)
    TYPE(ObjType), INTENT(inout) :: this
    ObjGet = this%var
 END FUNCTION ObjGet

END MODULE ObjMod


PROGRAM test

 USE ObjMod
 IMPLICIT NONE 

 TYPE (ObjType), POINTER :: testObj

 CALL ObjCreate(testObj)
 CALL ObjSet(testObj, 12)
 PRINT*, ObjGet(testObj)
 CALL ObjDelete(testObj)
 STOP
END PROGRAM test

I also used to code like that in C in the early 80s before a decent C++ compiler came out. What you will find is that many systems written in the 70s up to the early 90s use this technique. It will work in any language that supports structures and dynamic memory allocation.

于 2013-07-10T18:21:26.213 回答
2

你可以简单地写

SUBROUTINE set(an_int)
    integer, intent(inout) :: an_int
    an_int = 5
END SUBROUTINE set

然后像这样调用子程序:

CALL set(myObj%var)

我认为将组件打包成派生类型然后将它们解包以传递给过程是不正当的观点,这只是一种观点,您可以随意忽略它。就个人而言,我会更彻底地重写您的代码,如下所示。请注意,尽管这使用了 2003 标准中引入的一些功能,但这些功能已在最广泛使用的编译器的当前版本中实现。

MODULE mytype

  IMPLICIT NONE

  TYPE obj
     INTEGER, PRIVATE :: var
   CONTAINS
     PROCEDURE, PASS :: get_var
     PROCEDURE, PASS :: set_var
  END TYPE obj

CONTAINS

  SUBROUTINE set_var(this,an_int)
    CLASS(obj), INTENT(inout) :: this
    INTEGER, INTENT(in) :: an_int
    this%var = an_int
  END SUBROUTINE set_var

  INTEGER FUNCTION get_var(this)
    CLASS(obj), INTENT(inout) :: this
    get_var = this%var
  END FUNCTION get_var

END MODULE mytype


PROGRAM test

  USE mytype
  IMPLICIT NONE 

  TYPE (obj) :: myObj
  CALL myobj%set_var(12)
  PRINT*, myObj%get_var()

END PROGRAM test
于 2013-07-09T08:35:53.717 回答