声振论坛

 找回密码
 我要加入

QQ登录

只需一步,快速开始

查看: 2580|回复: 4

[Fortran] [求助]在fortran中如何实现函数返回类型控制

[复制链接]
发表于 2005-10-6 21:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?我要加入

x
在fortran里函数的返回类型一般都是固定的<BR>请问如何实现函数的返回类型随参数的变化而变化?谢谢
回复
分享到:

使用道具 举报

发表于 2005-10-7 19:04 | 显示全部楼层
fortran好像无法直接实现多态性吧。
发表于 2005-10-7 20:19 | 显示全部楼层
maybe I was wrong. sorry<br>
<br>
可以通过interface构造<br>

[此贴子已经被作者于2005-10-8 19:30:48编辑过]

发表于 2005-10-8 17:00 | 显示全部楼层
try this, compute_area根据传入参数的类型自动选择计算函数<br>
<br>
<div class="quote">module class_Rectangle<br>
  implicit none<br>
  type Rectangle<br>
     real :: base, height<br>
  end type Rectangle<br>
<br>
contains<br>
<br>
  function rectangle_area (r) result (area)<br>
    type(Rectangle), intent(in) :: r<br>
    real :: area<br>
    area = r%base * r%height<br>
  end function rectangle_area<br>
<br>
end module class_Rectangle<br>
<br>
<br>
module class_Circle<br>
  real :: pi = 3.1415926535897931d0<br>
  type Circle<br>
     real :: raidus<br>
  end type Circle<br>
<br>
contains<br>
  <br>
  function circle_area(c) result(area)<br>
    type(Circle), intent(in) :: c<br>
    real :: area<br>
    area = pi * c%raidus**2<br>
  end function circle_area<br>
  <br>
end module class_Circle<br>
<br>
<br>
program geometry<br>
  use class_Rectangle<br>
  use class_Circle<br>
  implicit none<br>
<br>
  interface compute_area<br>
     module procedure rectangle_area, circle_area<br>
  end interface<br>
<br>
  type(Rectangle) :: four_sides<br>
  type(Circle) :: two_sides<br>
  real :: area = 0.0<br>
<br>
  ! initialize a rectangel and compute area<br>
  four_sides = Rectangle(2.1, 4.3)<br>
  area = compute_area(four_sides)<br>
  write(*,*) four_sides, area<br>
<br>
  ! initialize a circle and compute area<br>
  two_sides = Circle(5.4)<br>
  area = compute_area(two_sides)<br>
  write(*,*) two_sides, area<br>
<br>
end program geometry<br>
<br>
</div>
<br>

[此贴子已经被作者于2005-10-8 17:04:37编辑过]

发表于 2005-10-8 19:28 | 显示全部楼层
另外一个例子, 交换两个实参. 很有趣呀.
[em07]<br>
<br>
module swap_module<br>
  implicit none<br>
  interface swap<br>
     module procedure swap_reals, swap_integers<br>
  end interface<br>
contains<br>
  subroutine swap_reals(a,b)<br>
    real :: a, b, temp<br>
    temp = a; a = b; b = temp;<br>
  end subroutine swap_reals<br>
  subroutine swap_integers(a,b)<br>
    integer :: a, b ,temp<br>
    temp = a; a = b; b = temp;<br>
  end subroutine swap_integers<br>
end module swap_module<br>
<br>
program test_swap<br>
  use swap_module<br>
  real :: x = 1.1, y = 2.2<br>
  integer :: i = 1, j = 2<br>
  call swap(x,y)<br>
  print *, x, y<br>
   call swap(i,j)<br>
  print *, i, j<br>
end program test_swap<br>
<br><br>
您需要登录后才可以回帖 登录 | 我要加入

本版积分规则

QQ|小黑屋|Archiver|手机版|联系我们|声振论坛

GMT+8, 2024-4-29 01:49 , Processed in 0.068967 second(s), 17 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表