0

I'm building a Function class in c++.

I have managed to overload the + and the cout operators.

I can do :

Fraction frac1 = {1, 2};
Fraction frac2 = {3, 4};
Fraction frac3 = frac1 + frac2;

std::cout << frac3; // returns "5/4"

I tried to do std::cout << frac1 + frac2 << endl;

But I couldn't...

I don't understand why I can't and how to do...

This is my full structure.


#include <iostream>

using std::cout;
using std::cin;
using std::endl;
using std::ostream;

struct Fraction {
    int numerator;
    int denominator;

    Fraction operator+(const Fraction frac) {
        Fraction endingFraction;

        if (denominator == frac.denominator) {
            endingFraction.numerator = numerator + frac.numerator;
            endingFraction.denominator = denominator;
        } else {
            endingFraction.numerator = numerator * frac.denominator + frac.numerator * denominator;
            endingFraction.denominator = denominator * frac.denominator;
        }

        int gcd = greatestCommonDivisor(endingFraction.numerator, endingFraction.denominator);

        endingFraction.numerator /= gcd;
        endingFraction.denominator /= gcd;

        return endingFraction;
    }

    friend ostream &operator<<(ostream &out, Fraction &frac) {
        cout << frac.numerator << "/" << frac.denominator;
        return out;
    }
};
tomPlanche
  • 21
  • 1
  • 6
  • 3
    when you write "I can't" I guess you mean "there is a compiler error". Please include it in the question together with a [mcve] of the problematic code – 463035818_is_not_a_number Oct 08 '21 at 13:40
  • 1
    Change `friend ostream &operator< – NathanOliver Oct 08 '21 at 13:43
  • 1
    A question like [this](https://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object) might also be relevant. In C++ a pure rvalue (like the temporary object created by `frac1 + frac2`) cannot be bound to a non-`const` lvalue reference (like the `frac` parameter in your `operator< – Nathan Pierson Oct 08 '21 at 13:47
  • Also minor suggestions: For `Fraction::operator+`, you can make the parameter a `const Fraction&` instead of taking it by value, and the member function itself can be `const` so the left hand side of a sum can be `const` and you can write things like `(f1 + f2) + f3`. – Nathan Pierson Oct 08 '21 at 13:56
  • thanks @NathanPierson !! – tomPlanche Oct 08 '21 at 13:56
  • thanks @NathanOliver !! – tomPlanche Oct 08 '21 at 13:57

0 Answers0