X hits on this document

# n_oop2.doc - page 4 / 14

60 views

0 shares

4 / 14

Rational operator* (const Rational& x, const Rational& y){

Rational z (x.num * y.num, x.den * y.den);

return z;

}

the objects x and y will not allow the function access to their private data members.  Here’s where the idea of a friend function comes in.

//Rational class w/ overloaded * operator in friend function

//Borland C++ 5.02

//Project Target Type: Application - Target Model: Console

//modified from Hubbard

#include <iostream>

class Rational {

friend Rational operator* (const Rational&, const Rational&);

public:

Rational (int=0, int=1);

Rational (const Rational&);

void print();

Rational& operator= (const Rational&);

private:

int num, den;

int gcd (int j, int k) {if (k==0) return j; return gcd(k, j%k);}

void reduce () {int g = gcd(num, den); num /= g; den /= g;}

};

int main(){

Rational x(22,7), y(-3, 8), z;

z = x;

cout << "\nz=  "; z.print();

x = y * z;

cout << "\nx=  "; x.print();

cout << "\n\n\nPress any key to close console window:  ";

char c; cin >> c;

return 0;

}

Rational::Rational (int n, int d) : num (n), den (d){

reduce();

}

Rational::Rational (const Rational& r) : num(r.num), den(r.den){

}

void Rational::print(){

cout << num << '/' << den;

}

Rational& Rational::operator= (const Rational& r){

num = r.num;

den = r.den;

 Document views 60 Page views 60 Page last viewed Sun Jan 22 17:03:17 UTC 2017 Pages 14 Paragraphs 547 Words 2961