AaronSpark 发表于 2005-10-6 21:22

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

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

FSI 发表于 2005-10-7 19:04

fortran好像无法直接实现多态性吧。

FSI 发表于 2005-10-7 20:19

maybe I was wrong. sorry<br>
<br>
可以通过interface构造<br>

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

FSI 发表于 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编辑过]

FSI 发表于 2005-10-8 19:28

另外一个例子, 交换两个实参. 很有趣呀.
<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>
页: [1]
查看完整版本: [求助]在fortran中如何实现函数返回类型控制