Question

i have a c++ class to handle fractions and i want it to allow conversion to double,
i have something like that :

class fraction  
{  
    double n,d;  
public:  
    fraction(double _n, double _d) {n = _n; d = _d;}  
    //some functions  
    double todouble() {return n/d;}  
};  

fraction frac(1,2);  
double dbl = frac.todouble();  

which works fine, but i want to overload the assignment operator so i can go directly with :

double dbl = frac;  

i tried to add this :

double double::operator =(double& dbl, fraction& frac) {return dbl = frac.n / frac.d;}  

which resulted in the following compilation error :

 error: ‘double fraction::operator=(double&, fraction&)’ must take exactly one argument  

what am i doing wrong?

Was it helpful?

Solution 3

If you want the ability to assign a double to fraction you can declare a non-explicit constructor:

fraction(double d = 0, double n = 1) : d(d), n(n) {}

and for reverse

operator double() const { return n/d; }

and then

fraction f;

f = 12.5;      // Assign a double to fraction

double x = f;  // Assign fraction as double to a double

OTHER TIPS

What you need is conversion operator:

operator double() const { return n / d; }

You cannot overload an assignment operator as a free function, meaning it must be a class member. Since double is no class, that means you have no way to write an assignment afor double.

The only thing that is left is writing a conversion operator for your class:

class Fraction {
  //...
public:
  double toDouble() const { return n/d; } 
  operator double() const { return toDouble(); } 
};

Having said that, this means you can use a fraction wherever you need a double, int, float, because the compiler uses the operator for implicit conversions, not only to double but also to int and other types that have possible builtin conversion from double. This can be desired for some classes, but it can lead to ambiguities and errors, because one often overlooks the conversion opportuinities the compiler takes into account.

In C++11 there is the possibility to make the operator explicit:

  explicit operator double() const { return toDouble(); } 

This would mean that implicit conversion are not allowed, and copy-initialization won't work, but direct initialization will:

 double dbl = frac;  //Error
 double dbl{frac};   //Ok 

A little sidenote: you should make that conversion function const.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top