I saw the following implementation of the operator* as follows:
class Rational {
public:
Rational(int numerator=0, int denominator=1);
...
private:
int n, d; // numerator and denominator
friend const Rational operator*(const Rational& lhs, const Rational& rhs)
{
return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
}
};
I have two questions here:
So that you can't do something like Rational a, b, c; (a * b) = c;
.
No.
Note that returning const Rational
instead of Rational
not only prevents nonsensical assignments but also move semantics (because Rational&&
does not bind to const Rational
) and is thus not recommended practice anymore in C++0x.
Scott Meyers wrote a note on this matter:
Declaring by-value function return values const will prevent their being bound to rvalue references in C++0x. Because rvalue references are designed to help improve the efficiency of C++ code, it's important to take into account the interaction of const return values and the initialization of rvalue references when specifying function signatures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With