【问题标题】:Fortran derived datatype used before defined定义前使用的 Fortran 派生数据类型
【发布时间】:2017-11-14 05:44:01
【问题描述】:

如何使用use module, ONLY:语句在模块之间包含派生数据类型(类型,而不是变量)?

更多描述:在我的module1 中,我定义了该数据类型的派生数据类型(我们称之为my_datatype)和一些数据(我们称之为my_data)。在我的module2 中,我需要使用my_data。由于我的 module1 包含许多 module2 不需要的过程,我想使用 ONLY 语句只包含 my_data。但是,如果不包括数据类型,它会给我错误:

Derive datatype 'my_type' is used before defined at "type(my_type),intent(out)::A"

很明显module2不能识别module1中定义的my_datatype,因为我没有通过。但是在“仅使用模块”语句中包含派生类型的语法是什么?我正在使用 Fortran 2003。

  module step1
  implicit none
     type my_type
        integer::id
        integer,dimension(2)::my_data
     end type my_type

     type(my_type)::A
  end module step1

  module step2
  use step1,only:A
  implicit none
  contains
     subroutine change_A(A)            
        type(my_type),intent(inout)::A
        A%id = 1
        A%my_data(1) = 1
        A%my_data(2) = 2                    
     end subroutine change_A
  end module step2

  program test
  ! program is in a different folder
  use step1
  use step2
     implicit none
     call change_A(A)
  end program test

【问题讨论】:

  • 欢迎。请在您的问题中发布真实代码。特别是在显示任何错误消息时这样做。此外,显示complete 错误消息。请参阅 How to Askminimal reproducible example。如果我删除废话并将my_data%i = 1 添加到do_something_to_my_data 中,您显示的代码编译得很好。您不需要范围内的数据类型来处理变量。
  • 谢谢弗拉基米尔。我已按照建议修改了问题。

标签: types module fortran derived


【解决方案1】:

但是,它给了我错误“在定义之前使用了派生数据类型”。看起来 module2 无法识别 module1 中定义的 my_datatype。

嗯,是的。当然 module2 不能识别您的数据类型,因为它是在 module1 中定义的,并且在您的“使用”语句中您说您只想使用变量 my_data。只需在“使用”语句中包含数据类型,它就会在模块 2 中知道

【讨论】:

  • 感谢您的快速回答。你能告诉我在“use”语句中使用数据类型的语法吗?我找不到它。
  • 与变量名完全相同。
【解决方案2】:

鉴于您更新的问题,以下是如何实施其他人建议的修复:

(编辑:实施 cmets 的建议:

  1. 只在模块 step2 中导入来自模块 step1 的类型。
  2. 在主程序中仅从 step1 导入 A 并从 step2 更改_A。
  3. 请注意,例程“change_A”中的虚拟参数“A”与例程定义中模块 step1 中的“A”无关。我更改了假人的名称来说明这一点。

)

module step1
  implicit none
  type my_type
     integer::id
     integer,dimension(2)::my_data
  end type my_type

  type(my_type)::A

end module step1

module step2
  use step1, only: my_type
  implicit none
contains
  subroutine change_A(dummy)
    type(my_type),intent(inout) :: dummy
    dummy%id = 1
    dummy%my_data(1) = 1
    dummy%my_data(2) = 2
  end subroutine change_A
end module step2

program test
  ! program is in a different folder
  use step1, only: A
  use step2, only: change_A
  implicit none

  call change_A(A)
  write(*,*) A

end program test

我在“使用”语句中添加了my_type

【讨论】:

  • 我认为值得明确指出子程序中的A 不是模块实体。
  • 是的,only 子句中的 A 几乎什么都不做。
猜你喜欢
  • 2012-10-23
  • 2019-03-02
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
相关资源
最近更新 更多