-1

I am making a class Fraction with global functions usage My code looks like below:

#include<iostream>
using namespace std;

ostream & operator<<(ostream & os, Fraction & fr)
{
    return os << fr.get_num() << '/' << fr.get_den();
}

class Fraction
{
private:
    int num, den;
public:
int get_num()
    {
        return num;
    }
    int get_den()
    {
        return den;
    }
};

Main function has call : `cout << f2 << endl;
But i am getting following build erros while compilation:
Error C2805 binary 'operator <<' has too few parameters
fr: undeclared identifier
left of get_num must be struct/union/class

ojas
  • 247
  • 1
  • 4
  • 17
  • 1
    Is that the only error you get? Nothing about `Fraction` being undeclared when you define the `operator<<` function? You do know that in C++ you must declare symbols before you use them? – Some programmer dude Mar 06 '16 at 05:35
  • 1
    Possible duplicate http://stackoverflow.com/questions/23335209/error-overloaded-operator-must-be-a-binary-operator-has-3-parameters – The Roy Mar 06 '16 at 06:18
  • 1
    you should also take `Fraction` by const reference – M.M Mar 06 '16 at 08:01
  • @DROY: thanks .. will check stack overflow other threads before posting :) – ojas Mar 06 '16 at 10:18

1 Answers1

1

You should change the order of your code like this:

class Fraction
{
private:
    int num, den;
public:
int get_num()
    {
        return num;
    }
    int get_den()
    {
        return den;
    }
};

ostream & operator<<(ostream & os, Fraction & fr)
{
    return os << fr.get_num() << '/' << fr.get_den();
}
stan
  • 129
  • 2