1
votes

so I'm working on a fraction class program, and I'm having a bit of difficulty overloading the output operator. the relevant bit of the main file.

const fraction fr[] = {fraction(4, 8), fraction(-15,21),
                       fraction(10), fraction(12, -3),
                       fraction(), fraction(28, 6), fraction(0, 12)};

for (int i = 0; i < 7; i++){
    cout << "fraction [" << i <<"] = " << fr[i] << endl;
}

and in the fraction.h

std::ostream& operator<<(std::ostream &out, const fraction &fr); //the location of the error. 

and in the class fraction.cpp file

ostream& operator<<(ostream& stream, const fraction& fr)
{
    if(fr.Denominator==1||fr.Numerator==0)
        stream << fr.Numerator;
    else
    stream << fr.Numerator << '/' << fr.Denominator << endl;
    return stream;
}

anyway, the error code is straightforward. ‘std::ostream& fraction::operator<<(std::ostream&, const fraction&)’ must take exactly one argument|

I am a bit lost as to why that's what it's telling me. [is it not able to accept functions that take 2 values?, is (std::ostream&, const fraction&) just plain wrong? should it just be a single argument in the parentheses?]

the main function is set in stone and works if my class's cpp and header file are coded correctly as it came with the assignment.

I've only ever done IO overloading in friend functions, never within, and even with those I'm inexperienced, so I'm pretty lost at this point.

1

1 Answers

1
votes

The compiler is telling you that you're trying to overload operator << for two arguments, but inside the class operator member functions take only one argument (that is, the righthand argument). Your code would work if it were a friend of fraction because you would be defining a free operator function which takes two arguments.

So to fix, either define the function outside fraction or name it as a friend of the class. When you name it as a friend, the function will be able to access private members of any instance of the class.