friend class
1. Create a friend class BestFriend to the class frac. Inside the class BestFriend, and implement a function outputfrac() to print the content of the frac instance.
2. Create a friend function outputfrac() to print the content of the frac instance for class GoodFriend to the class frac.
Starter: lab8_ex1_friend.cpp
#include <iostream>
#include <cstdlib> // labs()
using namespace std;
class frac; // Forward Declaration <--- necessary for using frac before it is defined
// Function Prototypes for Overloaded Stream Operators
ostream &operator << (ostream &, const frac &);
istream &operator >> (istream &, frac &);
// Define the GoodFriend class which has a Friend outputfrac()
class GoodFriend
{
// ---> define the GoodFriend class
};
class frac {
//private:
long num;
long den;
public:
// constructors
frac() {
num = 0;
den = 1;
}
frac(long n, long d) {
num = n;
den = d;
}
frac(const frac &f) {
num = f.num;
den = f.den;
}
// accessors and mutators
long getNum() {return num;}
long getDen() {return den;}
void setNum(long n) {num = n;}
void setDen(long d) {den = d;}
// auxiliary method
void outputfrac() {std::cout << ' ' << num << '/' << den << ' ';}
// Friends - overload stream operators
friend ostream &operator << (ostream &strm, const frac &f)
{
strm << f.num << '/' << f.den;
return strm;
}
// Friend class ---> BestFriend prototype here
// Friend function ---> GoodFriend::outputfrac() prototype here
};
//--------------------------------------------------------------
// Friend class to frac - method definition here
class BestFriend
{
// ---> define the best friend class with outputfrac() here
};
void GoodFriend::outputfrac(frac &f) {
// ----> define this friend's outputfrac() here
}
int main()
{
// testing friendship
frac f(3,8);
BestFriend bf;
bf.outputfrac(f);
GoodFriend gf;
gf.outputfrac(f);
cout << f ;
return 0;
}
12 years ago
Purchase the answer to view it

- friend_class.cpp