home *** CD-ROM | disk | FTP | other *** search
/ Microsoftware Monthly 19…2 Programming Power Tools / MASO9512.ISO / cpptutor / cpptutor.arj / EXAMPLES / EX0804.CPP < prev    next >
Encoding:
C/C++ Source or Header  |  1993-10-05  |  2.0 KB  |  64 lines

  1. // \EXAMPLES\EX0804.CPP
  2. // main program to demonstrate members that are objects
  3. //---------------------------------------------------------
  4. // files in this example:
  5. // %F,15,EX0804.H%EX0804.H        definition of Fraction class
  6. // EX0804.CPP      main program
  7. //---------------------------------------------------------
  8. #include <iostream.h>                // stream I/O
  9. #include <process.h>                 // for abort()
  10.  
  11. #include "EX0804.H"                  // def'n of Fraction class
  12.  
  13. //---------------------------------------------------------
  14. // the Pfracton class has a member that is a fraction
  15. //---------------------------------------------------------
  16. class Pfraction{
  17.   int whole;
  18.   Fraction part;
  19. public:
  20.   Pfraction(int n, int d);
  21.   ~Pfraction() {};
  22.   friend void print(const Pfraction& pf);
  23. };
  24.  
  25. //---------------------------------------------------------
  26. // constructor with initializer list
  27. // this initializer list assumes d != 0
  28. //---------------------------------------------------------
  29. Pfraction::Pfraction(int n=0, int d=1) : whole(n/d), part(n%d, d)
  30. { if ( whole < 0 ) part = - part;
  31. }
  32.  
  33. //---------------------------------------------------------
  34. //---------------------------------------------------------
  35. void main()
  36. {  // user input separate numerator and denominator
  37.    int n, d;
  38.    cout << "Enter int numerator and denominator:  ";
  39.    cin >> n >> d;
  40.    if ( d == 0 )
  41.    {  cout << " 0 denominator not allowed: ";
  42.       abort();
  43.    }
  44.    // construct and print the proper fraction
  45.    Pfraction k(n,d);
  46.    cout << endl << "The proper fraction is: ";
  47.    print(k);
  48.    cout << endl;
  49. }
  50.  
  51. //---------------------------------------------------------
  52. //  friend of the Pfraction class
  53. //---------------------------------------------------------
  54.  
  55. void print (const Pfraction& pf)
  56. {  cout << pf.whole << '_';
  57.    print(pf.part);
  58. }
  59.  
  60. void print (const Fraction& f)
  61. {  cout << f.num << '/' << f.denom;
  62. }
  63. //---------------------------------------------------------
  64.