C ++ typecasting vs implicit constructor

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);

+4
source share
2 answers

By definition, conversion operators are implicit. You cannot make them explicit.

A normal solution is called member functions for conversion. I think you can also create a specialized template method that looks just like static_cast and call an explicit class method.

+3
source

Remove the conversion operators, and 3 + a should use your friend operator+ , implicitly converting 3 to Fraction via the implicit constructor Fraction(int i); .


Change In the case of explicit conversion operators, C ++ 0x specifically allows this:

12.3.2 [class.conv.fct] p2
The transform function can be explicit, in which case it is only considered as a user transform for direct initialization.

The C ++ 03 standard does not specifically mention this.

+3
source

All Articles