Reputation: 75
So I wrote this overloaded function for fraction class that has variables num and den.
fraction operator +(fraction & f1, fraction & f2)
{
fraction temp;
temp.num = (f1.num * f2.den ) + ( f1.den * f2.num );
temp.den = (f1.den * f2.den );
return temp;
}
If i use this code as f1 = f1+f2
, it runs fine.But I want to use it as f1 = f2+fraction(3,4)
If I try to use it this way, it shows invalid operands to fraction and fraction.
Can anyone identify this kind of error and why it occurs. Thanks in advance.
Upvotes: 2
Views: 47
Reputation: 7090
I usually code a +=
and then a +
operator in terms of that. For example:
// member function
fraction &fraction::operator +=(const fraction &f2)
{
num = num * f2.den + den * f2.num;
den *= f2.den;
}
// non-member function
inline fraction operator+(fraction lhs, const fraction& rhs)
{
lhs += rhs;
return lhs;
}
Note that in the second function, lhs
is not a reference but a copy of the passed fraction
. It is a modified version of the copy that is returned by the function. The non-member function can almost always be written exactly that way.
Upvotes: 0
Reputation: 172934
The type fraction&
requires the argument passed must be an lvalue (an object whose address
you can take) of type fraction
. But fraction(3,4)
is a temporary object, not a lvalue, so it can't be passed by reference.
But const fraction &
need not an lvalue, the temporary variable could be used as the value.
And f1
and f2
will not be changed in operator +
, so you could and should change the parameter declaration to const &
, which allow the temporary object passed by reference.
fraction operator +(const fraction & f1, const fraction & f2)
Upvotes: 5