-1

I am trying to overload the >> operator so that when the user inputs a fraction, cin would store the fraction into an Object of type Fraction.
Excerpt from header file:

// Calculator.h
friend istream &operator>>( istream &, Fraction &);

private:
    signed int numo; // fraction numerator
    signed int deno; // fraction denomenator
    char ch; // the '/' character

Excerpt from Implementation file:

 //Calculator.cpp

// insertion operator overloading
istream &operator>>( istream &input, Fraction fraction)
{
    input >> fraction.numo;
    input >> fraction.ch;
    input >>fraction.deno;

    return input; 
}

When I try to compile Calculator.cpp and compile a driver function inside another file, I run into many errors. Why is this not working? Please explain your answer thoroughly, I would like to learn.

UPDATE:
**Errors: variables, numo deno and ch are 'private'

Andy_A̷n̷d̷y̷
  • 795
  • 2
  • 11
  • 25

2 Answers2

5

You have a simple mismatch. The function that's declared as a friend takes a reference to a Fraction as its second parameter. The function you've implemented takes a fraction by value instead, so it's not a friend of the Fraction class. You want the version that takes a reference since when you use the function you normally want to pass a variable, and you want it to modify that variable.

I usually prefer to implement such things in place:

class Fraction { 

     friend std::istream &operator>>(std::istream &is, Fraction &f) { 
        return is >> f.numo >> f.ch >> f.deno;
     }

     // ...
};

Even though its body is inside the class definition, this is still a non-member function simply by virtue of the fact that it's declared as a friend.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

Andy in Calculator.h header file, you are using Fraction& (ref type) as function second argument. So in function definition it must be same, (don't use value type).

Prototype:

friend istream& operator>>(istream&, Fraction ); 

Function definition:

istream& operator>>(istream& input, Fraction& fraction)
{
    input >> fraction.numo;
    input >> fraction.ch;
    input >>fraction.deno;

    return input; 
}
Community
  • 1
  • 1