home *** CD-ROM | disk | FTP | other *** search
- // \EXAMPLES\EX0801.CPP
- // main program to demonstrate friend functions
- //---------------------------------------------------------
- // files in this example:
- // %F,15,EX0801.H%EX0801.H definition of Fraction class
- // EX0801.CPP main program
- //---------------------------------------------------------
- #include <iostream.h> // stream I/O
- #include <strstrea.h> // #include <strstream.h>
- #include "EX0801.H"
-
- void print(const Fraction& f);
- void read(Fraction& f);
-
- void main()
- { Fraction f; // declare a fraction
- cout << "Enter a fraction n/d: ";
- read(f); // read a fraction
- cout << "print()\t";
- print(f); // output using friend
- cout << endl;
- cout << "display()\t ";
- f.display(); // output using member
- cout << endl;
- cout << "<<\t";
- cout << f << endl; // output using <<
- }
-
- // functions -- friends of the fraction class
-
- void print(const Fraction& f)
- { cout << f.num << "/" << f.denom;
- }
-
- void read(Fraction& f)
- { char c; // to hold the '/'
- f.num = 0; // default numerator
- f.denom = 1; // default denominator
- char buffer[20]; // for reformatting
- ostrstream oss(buffer,26,ios::out); // in-memory output
- istrstream iss(buffer,26); // in-memory input
- char token[20]; // to hold raw input
- cin >> token; // read as string
- oss << token << "/1" << ends; // write to memory
- iss >> f.num >> c >> f.denom; // read int-char-int
- if ( c != '/' ) f.denom = 1; // check syntax n/d
- f.reduce(); // simplify fraction
- }
-
- ostream& operator<<( ostream& os, const Fraction& f)
- { os << f.num << "/" << f.denom;
- return os;
- }