I am implementing a C ++ class representing a fraction. Here is my code.
class Fraction { public: Fraction(char i); Fraction(int i); Fraction(short i); Fraction(long int l); #ifdef __LP64__ Fraction(long long l); #endif Fraction(float f); Fraction(double d); Fraction(double x, double y); Fraction operator +() const; Fraction operator -() const; Fraction& operator +=(const Fraction& other); Fraction& operator -=(const Fraction& other); Fraction& operator *=(const Fraction& other); Fraction& operator /=(const Fraction& other); bool operator ==(const Fraction& other); bool operator !=(const Fraction& other); bool operator >(const Fraction& other); bool operator <(const Fraction& other); bool operator >=(const Fraction& other); bool operator <=(const Fraction& other); operator double(); operator float(); static void commonize(Fraction& a, Fraction& b); void shorten(); double getNumerator(); double getDenominator(); friend Fraction operator +(Fraction const& a, Fraction const& b); friend Fraction operator -(Fraction const& a, Fraction const& b); friend Fraction operator *(Fraction const& a, Fraction const& b); friend Fraction operator /(Fraction const& a, Fraction const& b); friend ostream& operator <<( ostream& o, const Fraction f); protected: double numerator, denominator; };
Now I have two problems. Now trying to call
Fraction a(1, 2); cout << (3 + a) << endl;
just leads to this error:
fractiontest.cpp:26: error: ambiguous overload for 'operator+' in '3 + a' fractiontest.cpp:26: note: candidates are: operator+(int, double) <built-in> fractiontest.cpp:26: note: operator+(int, float) <built-in>
All I really want is the following:
explicit operator double(); explicit operator float();
But apparently this does not work. I would like these two operator statements to be called if I use cast notation. For example Fraction f(1, 2); double d = (double)(f); Fraction f(1, 2); double d = (double)(f);
source share