我有一个类似的代码:
Module C_sys
use class_A
implicit none
Private
Type, public :: C_sys_type
private
logical :: Ao_set = .false.
type(A) :: Ao
Contains
Private
Procedure, public :: get_Ao
Procedure, public :: set_Ao
End Type C_sys_type
interface C_sys_type
Procedure C_sys_type_constructor
end interface C_sys_type
Contains
type(C_sys_type) elemental function C_sys_type_constructor(Ao) result(C_sys)
type(A), intent(in), optional :: Ao
C_sys % Ao = Ao
C_sys % Ao_set = .true.
end function C_sys_type_constructor
type(A) elemental function get_Ao
class(C_sys_type), intent(in) :: this
get_Ao = this % Ao
end function get_Ao
subroutine set_Ao(this, Ao)
class(C_sys_type), intent(inout) :: this
type(Ao), intent(in) :: Ao
this % Ao = Ao
this % Ao_set = .true.
end subroutine set_Ao
End Module C_sys
我不确定子例程中的 set_Ao 、 type(Ao)、intent(in) :: Ao 应该像这样保留,或者改为 class(Ao)、intent(in) :: Ao。我知道 class(Ao) 正在使变量多态并访问 A 的数据类型。但我不知道何时必须使用其中之一。
Thanks.
如果您希望能够将函数/子例程绑定到派生类型(并且该例程能够访问/修改该类型实例的成员,这是通常的用例;称为“PASS
ing”变量),需要满足以下条件:
- The
TYPE
定义必须包含适当的PROCEDURE
线(或者与PASS
明确说明,或者默认情况下NOPASS
未指定)。
- The function/subroutine have at least one dummy argument of the
TYPE
in question, which must be declared in the argument list with CLASS
(subject to all the restrictions that entails).
- The reason它需要
CLASS
因为这是其他一些TYPE
可能会“延长”你的TYPE
,这意味着它继承其成员 - 这只有在成员例程是数据多态的情况下才有效。
我尝试将您提供的代码示例修改为代表我认为您实际含义的内容,但实际上可以编译,以希望演示正确的用法。
module c_sys
implicit none
private
type, public :: a
integer :: i
end type
type, public :: c_sys_type
private
logical :: ao_set = .false.
type(a) :: ao
contains
private
procedure, public :: get_ao
procedure, public :: set_ao
end type c_sys_type
interface c_sys_type
procedure c_sys_type_constructor
end interface c_sys_type
contains
type(c_sys_type) elemental function c_sys_type_constructor(ao) result(c_sys)
type(a), intent(in), optional :: ao
c_sys % ao = ao
c_sys % ao_set = .true.
end function c_sys_type_constructor
type(a) elemental function get_ao(this)
class(c_sys_type), intent(in) :: this
get_ao = this % ao
end function get_ao
subroutine set_ao(this, ao)
class(c_sys_type), intent(inout) :: this
type(a), intent(in) :: ao
this % ao = ao
this % ao_set = .true.
end subroutine set_ao
end module c_sys
- 我假设你的
TYPE A
and TYPE AO
被定义在CLASS_A
您尚未提供的模块。我在我的版本中声明了一个虚拟类型。
如果你想利用,事情会变得更加复杂NOPASS
等等,但对于“正常”使用,我希望这能回答您的问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)