! Copyright J. E. Akin, 1997
! F90 Implementation of a Rational Class Constructors & Operators
!
! Reference: Examples 8.1,4,7,8,9,11 pages 221,4,6,7,8,230
! Examples 9.2,4,5,7 pages 250,2,3,4
! Schaum's Outline of Programming with C++ by John R. Hubbard
include 'class_Rational.f90'
program main
use class_Rational
implicit none
type (Rational) :: x, y, z
! ------- only if Rational is NOT private ----------
! x = Rational(22,7) ! intrinsic constructor if public components
x = Rational_(22,7) ! public constructor if private components
write (*,'("public x = ")',advance='no'); call list(x)
write (*,'("converted x = ", g9.4)') convert(x)
call invert(x)
write (*,'("inverted 1/x = ")',advance='no'); call list(x)
x = make_Rational () ! default constructor
write (*,'("made null x = ")',advance='no'); call list(x)
y = 4 ! rational = integer overload
write (*,'("integer y = ")',advance='no'); call list(y)
z = make_Rational (22,7) ! manual constructor
write (*,'("made full z = ")',advance='no'); call list(z)
! Test Accessors
write (*,'("top of z = ", g4.0)') get_numerator(z)
write (*,'("bottom of z = ", g4.0)') get_denominator(z)
! Misc. Function Tests
write (*,'("making x = 100/360, ")',advance='no')
x = make_Rational (100,360)
write (*,'("reduced x = ")',advance='no'); call list(x)
write (*,'("copying x to y gives ")',advance='no')
y = copy_Rational (x)
write (*,'("a new y = ")',advance='no'); call list(y)
! Test Overloaded Operators
write (*,'("z * x gives ")',advance='no'); call list(z*x) ! times
write (*,'("z + x gives ")',advance='no'); call list(z+x) ! add
y = z ! overloaded assignment
write (*,'("y = z gives y as ")',advance='no'); call list(y)
write (*,'("logic y == x gives ")',advance='no'); print *, y==x
write (*,'("logic y == z gives ")',advance='no'); print *, y==z
! Destruct
call delete_Rational (y) ! actually only null it here
write (*,'("deleting y gives y = ")',advance='no'); call list(y)
end program main ! Running gives:
! public x = 22 / 7 ! converted x = 3.143
! inverted 1/x = 7 / 22 ! made null x = 0 / 1
! integer y = 4 / 1 ! made full z = 22 / 7
! top of z = 22 ! bottom of z = 7
! making x = 100/360, reduced x = 5 / 18
! copying x to y gives a new y = 5 / 18
! z * x gives 55 / 63 ! z + x gives 431 / 126
! y = z gives y as 22 / 7 ! logic y == x gives F
! logic y == z gives T ! deleting y gives y = 0 / 1
fortran OOP(6) Test_Rational.f90
最新推荐文章于 2022-04-10 22:26:13 发布