-1

I'm getting some errors (which are shown below) I'm not exactly sure what is causing these errors. I looked through my teachers example code and I can't find anything that I'm doing that is causing this error.

I've also tried searching up the error and adjusting the code but have gotten nothing. I would appreciate some assistance with where I'm going wrong. Thank you!

// error
Rational.cpp:60:10: error: cannot bind non-const lvalue reference of type ‘Rational&’ to an rvalue of type ‘Rational’
return Rational(num, den);
       ^~~~~~~~~~~~~~~~~~

// in Rational.h
Rational add(const Rational &r) const;

// in Rational.cpp
Rational Rational::add(const Rational &r) const
{
    int num = (numerator * r.denominator) + (denominator * r.numerator);
    int den = denominator * r.denominator; 

    return Rational(num, den);
}

p.s. I'm doing intro to C++, so I would appreciate simpler terms and explanations!

Amai
  • 141
  • 6

1 Answers1

4

The constructor is defined as Rational::Rational(Rational&) when it should take a const reference. You cannot bind a temporary to a non-const reference, and add returns a temporary. To use that temporary to initialize a newly-constructed rational, the constructor needs to take a non-const reference.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278