home *** CD-ROM | disk | FTP | other *** search
/ C by Discovery (4th Edition) / C_By_Discovery_4th_Edition.tar / C_By_Discovery_4th_Edition / _DISK_ / ch12 / fraction.cpp < prev    next >
C/C++ Source or Header  |  2005-06-16  |  1KB  |  56 lines

  1. //                   fraction.cpp
  2. //
  3. // Contains an implementation of the function
  4. // members of the Fraction class
  5.  
  6. // Include Files
  7. #include <iostream.h>
  8. #include "fraction.h"
  9.  
  10. Fraction::Fraction ( int n, int d )
  11. {
  12.     if ( d != 0 ) {
  13.         if ( d > 0 ) {
  14.             num = n;
  15.             denom = d;
  16.         }
  17.         else {
  18.             num = -n;
  19.             denom = -d;
  20.         }    
  21.     }
  22.     else {
  23.         num = 0;
  24.         denom = 1;
  25.     }
  26. }
  27.  
  28. Fraction Fraction::operator -() const                // Note 1
  29. {
  30.     Fraction tmp( -num, denom );
  31.     if ( tmp.denom < 0 ) {
  32.         tmp.num = -tmp.num;
  33.         tmp.denom = -tmp.denom;
  34.     }
  35.     return tmp;
  36. }
  37. Fraction Fraction::operator +( Fraction f ) const    // Note 2
  38. {
  39.     Fraction tmp;
  40.  
  41.     tmp.num = num*f.denom + denom*f.num;
  42.     tmp.denom = denom * f.denom;
  43.  
  44.     if ( tmp.denom < 0 ) {
  45.         tmp.num = -tmp.num;
  46.         tmp.denom = -tmp.denom;
  47.     }
  48.     return tmp;
  49. }
  50.  
  51. ostream& operator << ( ostream& str, Fraction f )    // Note 3
  52. {
  53.     str << f.num << "/" << f.denom;
  54.     return str;
  55. }
  56.