I have the following in my header file:
template<typename T>
class rational {
private:
T num;
T denom;
T gcd(T x, T y);
public:
rational(T num, T denom);
rational(T wholeNumber);
template<typename U>
friend inline rational<U> operator *(const rational<U> &lhs, const rational<U> &rhs);
}
template<typename T>
rational<T>::rational(T whole) {
this->num = whole;
this->denom = 1;
}
template<typename T>
rational<T> operator *(const rational<T> &lhs, const rational<T> &rhs) {
return rational<T>(lhs.num * rhs.num, lhs.denom * rhs.denom);
}
And the following in my main:
rational<int> x(6), y(2);
rational<int> product = y * x; // this works
rational<int> product2 = 2 * x; // this doesn't
The first product works, but the second one gives me "error: no match for ‘operator*’ in ‘2 * x’". Why? Since there is a constructor available that takes only the 2 as an argument, shouldn't that be automatically called? If not, how else would I overload the operator to have both of these work?
Thanks.