dimanche 6 octobre 2019

Overriding iostream << results in error - C++ 11

I am creating a class of Rational fractions like many others have before for a C++ Learning exercise.

One of my requirements is to override the << operator so that I can support printing the "fraction", i.e. numerator + '\' + denominator

I have tried following this example, and that seems to be in line with this example and this example, yet I still get compilation errors:

WiP2.cpp:21:14: error: 'std::ostream& Rational::operator<<(std::ostream&, Rational&)' must have exactly one argument
   21 |     ostream& operator << (ostream& os, Rational& fraction) {
      |              ^~~~~~~~
WiP2.cpp: In function 'int main()':
WiP2.cpp:39:24: error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'Rational')
   39 |     cout << "Two is: " << two << endl;
      |     ~~~~~~~~~~~~~~~~~~ ^~ ~~~
      |          |                |
      |          |                Rational
      |          std::basic_ostream<char>

My code is below:

#include <iostream>
using namespace std;

class Rational
{
    /// Create public functions
    public:

    // Constructor when passed two numbers
    explicit Rational(int numerator, int denominator){
        this->numerator = numerator;
        this->denominator = denominator;    
    }

    // Constructor when passed one number
    explicit Rational(int numerator){
        this->numerator = numerator;
        denominator = 1;    
    }

    ostream& operator << (ostream& os, Rational& fraction) {
    os << fraction.GetNumerator();
    os << '/';
    os << fraction.GetDenominator();

    return os;
    }

    private:
    int numerator;
    int denominator;
}; //end class Rational


int main(){
    Rational two (2);
    Rational half (1, 2);
    cout << "Hello" << endl;
    cout << "Two is: " << two << endl;
}

Why am I unable to use the override function in the Rational class to override the << operator?

Edit - I see some are suggesting the use of a friend. I don't know what that is, and am doing some preliminary investigation. A possible working comparison of using a friend for my situation could be beneficial to me as OP and others who are faced with similar implementation-type problems.

Aucun commentaire:

Enregistrer un commentaire