oop - fortran 中的过程 nopass 与普通函数

标签 oop static fortran

因此,在其他语言中,静态方法可以访问静态成员,并且它们的可见性受到类范围的限制。在 Fortran 中,没有静态成员(如果我错了,请纠正我)并且方法名称是全局可访问的,因此我什至不能在不同的类中拥有两个同名的静态方法。我认为“nopass”方法是“静态”的,但我什至不确定该术语是否适用。鉴于上述情况,我认为与普通的模块函数没有任何区别。与普通函数相比,使用 nopass-methods 有什么好处吗?

编辑:

说明无法在不同的类中使用两个同名的静态方法:

module test_mod
  type type1
  contains
    procedure, nopass :: proc => proc1
  end type

  type type2
  contains
    procedure, nopass :: proc => proc2
  end type

contains
  subroutine proc1()
    print *, 'proc1'
  end subroutine

  subroutine proc2()
    print *, 'proc2'
  end subroutine
end module

显然,我现在不能只说call proc(),也不能使用类名来帮助编译器选择正确的方法。

最佳答案

考虑可访问性:只要类型可访问,公共(public)类型绑定(bind)过程就可以访问。

module mod
  private
  type, public :: type1
  contains
    procedure, nopass :: proc
  end type

contains

  subroutine proc
  end subroutine

end module

  use mod
  type(type1) t1

  call t1%proc
  call proc  ! No, we can't call proc from mod1

end

类似地,使用 use <module>, only <...>

module mod1
  type type1
  contains
    procedure, nopass :: proc
  end type

contains

  subroutine proc
  end subroutine

end module

module mod2
  type type2
  contains
    procedure, nopass :: proc
  end type

contains

  subroutine proc
  end subroutine

end module

我们可以避免模块过程名称的冲突,而无需在使用关联时重命名:

  use mod1, only : type1
  use mod2, only : type2

  type(type1) t1
  type(type2) t2

  call t1%proc
  call t2%proc    ! These aren't ambiguous

end

为了避免程序出现歧义,我们必须重命名:

  use mod1, proc1=>proc
  use mod2, proc2=>proc

  call proc1
  call proc2

end

还有过程引用的动态选择:

module mod
  type type1
  contains
    procedure, nopass :: proc=>proc1
  end type

  type, extends(type1) :: type2
  contains
    procedure, nopass :: proc=>proc2
  end type

contains

  subroutine proc1
  end subroutine

  subroutine proc2
  end subroutine

end module

use mod
class(type1), allocatable :: t

t=type1()
call t%proc  ! proc1

t=type2()
call t%proc  ! proc2

end

但应该注意的是,像 t1%proc 这样的绑定(bind)名称与过程名称不同

 use mod
 type(type1) t1
 call sub(proc1)    ! Where this is accessible
 call sub(t1%proc)  ! We cannot do this

contains

 subroutine sub(proc)
   procedure() proc
 end subroutine

end

关于oop - fortran 中的过程 nopass 与普通函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44251213/

相关文章:

java - 验证由另一个参数确定的构造参数

php - 我应该在 php __destruct() 中使用 unset 吗?

javascript - @SpringBootApplication 不加载静态文件

c++ - 如何在不同的 dll 中强制销毁静态对象的顺序?

fortran - 检查传递给函数的数组的大小

c - 混合编程 : Calling FORTRAN from C

快速计算R中的二重积分

c++ - 通过只读迭代器公开成员数据

java - Java中是否有必要在每个类中都有一个构造函数

c++ - C++17 中的双向静态值映射