0

I'm trying to overload the output << operator for my custom class Fraction

but I'm facing this strange error:

too many parameters for this operator function

I looked at example for that but I have nearly the same implementation:

https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx

I'm using visual studio 2015 community edition

this is my code for now:

#pragma once
#include <ostream>

using namespace std;

class Fraction
{
    double denominator_;

    double numerator_;

    public:
        Fraction(const double& denominateur, const double& numerateur)
            : denominator_(denominateur), numerator_(numerateur)
        {

        }

        double getDenominator() const
        {
            return denominator_;
        }

        double getNumerator() const
        {
            return numerator_;
        }

        double getValue() const
        {
            return getNumerator() / getDenominator();
        }

        ostream& operator<<(ostream& output, const Fraction& frac ) const 
        {
            output << frac.getNumerator() << "/" << frac.getDenominator();
            return output;
        }
};

can some one figure out what is the problem ?

linuxD
  • 27
  • 2
  • 12

1 Answers1

1

Make it a free function and not a member function. If you need access to private members of the class, you can make it a friend. The error appears, because non-static member functions implicitly take a pointer to a class instance as first parameter.

Actually the operator you wrote would be used as

Fraction f,g;
f.operator<<(std::cout,g);

But what you want is

std::cout.operator<<(f);
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185