Fortran动态字段参考?

时间:2015-11-11 02:04:35

标签: oop fortran fortran90 derived-types

是否可以动态引用Fortran中的派生类型字段?我想在Matlab中实现可以实现的效果:

fldnm = 'fred';
s.(fldnm) = 18;
y = s.(fldnm) 

请参阅以下链接(适用于Matlab示例): http://blogs.mathworks.com/loren/2005/12/13/use-dynamic-field-references/ http://www.mathworks.com/help/matlab/matlab_prog/generate-field-names-from-variables.html

谢谢!

1 个答案:

答案 0 :(得分:2)

没有。也许您需要将字段名称和值都存储在数据对象中,而不是尝试使用组件作为字段名称。

否则,您需要使用SELECT CASE语句或类似语句来包装派生类型对象的组件的引用或定义。

TYPE :: t
  INTEGER :: fred
  INTEGER :: roger
  INTEGER :: bill
END TYPE t

SUBROUTINE set(object, name, value)
  TYPE(t), INTENT(INOUT) :: object
  CHARACTER(*), INTENT(IN) :: name
  INTEGER, INTENT(IN) :: value
  SELECT CASE (name)
  CASE ('fred')  ; object%fred = value
  CASE ('roger') ; object%roger = value
  CASE ('bill')  ; object%bill = value
  END SELECT
END SUBROUTINE set

FUNCTION get(object, name)
  TYPE(t), INTENT(IN) :: object
  CHARACTER(*), INTENT(IN) :: name
  INTEGER :: get
  SELECT CASE (name)
  CASE ('fred')  ; get = object%fred
  CASE ('roger') ; get = object%roger
  CASE ('bill')  ; get = object%bill
  END SELECT
END FUNCTION get

TYPE(t) :: s
CALL set(s, 'fred', 18)
y = get(s, 'fred')