X hits on this document

44 views

0 shares

0 downloads

0 comments

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.

//overloading2.cpp

//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;

overloading.doc4 of 14

Document info
Document views44
Page views44
Page last viewedMon Dec 05 17:07:45 UTC 2016
Pages14
Paragraphs547
Words2961

Comments