Reputation: 852
Hey, I would like to know the difference between these 2 operator definitions:
1:
class Rational{
//...
public:
//...
Rational operator -() const{ return Rational(-t,b);}
//...
};
2:
class Rational{
//...
public:
//...
friend Rational operator -(const Rational& v) {return Rational(-t,b);}
//...
};
as far as i understand, for the usage of:
Rational s = -r
r.operator-() // should happen
would like some explenation for the difference, thanks !
Upvotes: 0
Views: 613
Reputation: 103505
For the most part, they are the same.
First of all, I don't think you have either written right. They should be:
// Member function. "-r" calls r.operator-()
Rational Rational::operator -() const{ return Rational(-t,b);}
// (technically a) global function. "-r" calls ::operator-(r)
friend Rational operator -(const Rational& v) {return Rational(-v.t,v.b);}
The major difference is that if you have another type (say MyRational
) which is convertible to a Rational object, then:
MyRational mr = MyRational();
Rational r = -mr;
will work with the second definition, but not for the first.
Upvotes: 3