fortran - Fortran 2008 中的函数重载

标签 fortran polymorphism overloading fortran2008

我从 Fortran 2008 开始,我在 OOP 方面遇到了很大的困难。似乎很少有资料可以解释 2008 语言标准中一个非常基本的 OOP 概念。

我找到了有关继承的信息,但找不到有关多态性的任何信息。

因此,如果我想在 C++ 中重载一个函数,我可以这样做(来自 Wikipedia 的示例):

// volume of a cube
int volume(const int s)
{
    return s*s*s;
}

// volume of a cylinder
double volume(const double r, const int h)
{
    return 3.1415926*r*r*static_cast<double>(h);
}

// volume of a cuboid
long volume(const long l, const int b, const int h)
{
    return l*b*h;
}

但是,我应该如何在 Fortran 2008 中做同样的事情?

最佳答案

C++ 示例中给出的重载思想在 Fortran 中有一个实现,可以追溯到 Fortran 90 的泛型。

给定一组特定程序,可以使用通用标识符来标识该组。在这个答案中,我将对这个概念进行非常高级的介绍。有很多微妙之处可能需要进一步阅读/解决问题。

与 C++ 示例不同,我们的 Fortran 特定过程需要单独命名。让我们有两个功能(第三个可以比照添加)

integer function volume_cube(s)
  integer, intent(in) :: s
  ...
end function volume_cube

double precision function volume_cylinder(r, h)
  double precision, intent(in) :: r
  integer, intent(in) :: h
  ...
end function volume_cylinder

然后我们可以为一个叫做 volume 的东西添加一个通用接口(interface)。 :
interface volume
  procedure volume_cube, volume_cylinder
end interface

然后我们可以引用泛型 volume并且编译器将确定使用哪个特定函数。

关于泛型还有很多需要了解,包括除了这个简单的重载之外它们还提供了什么。人们还应该了解如何解决特定程序(在这种情况下很简单,在其他情况下则不然)以及对哪些特定程序可能混为一谈的限制。当您使用泛型时,有问题的案例可能会有特定的问题。我在这里回答只是因为我看不到一个介绍性的问题,并且我不试图解决许多不同的困难或值(value)观。

完整示例
module mod

  private

  interface volume
     module procedure volume_cube, volume_cylinder
  end interface volume
  public volume

contains
  integer function volume_cube(s)
    integer, intent(in) :: s
    volume_cube = s**3
  end function volume_cube

  double precision function volume_cylinder(r, h)
    double precision, intent(in) :: r
    integer, intent(in) :: h
    volume_cylinder = 3.1415926d0*r**2*h
  end function volume_cylinder

end module mod

  use mod

  print*, volume(2), volume(2d0,4)
end

关于fortran - Fortran 2008 中的函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50581324/

相关文章:

fortran - ifort 和 gfortran 之间令人费解的性能差异

fortran - 在声明类型中分配参数声明类型时,ifort 出现灾难性错误

loops - 在另一个循环停止的地方开始一个循环

c++ - 生命游戏,C++ - 多态数组(也许还有指针)

c++ - 调用正确的重载父方法

c# - Debug.WriteLine 重载似乎有冲突

fortran - gfortran 错误 : zgesvd in lapack

c++ - 方法覆盖和重载

C union 和多态性

Java:重载方法解析