The question about the assignment operator in C ++

Forgive what may seem like a very simple question to some, but I have this use case:

struct fraction {
    fraction( size_t num, size_t denom ) : 
        numerator( num ), denominator( denom )
    {};
    size_t numerator;
    size_t denominator;
};

      

What I would like to do is use expressions such as:

fraction f(3,5);
...
double v = f; 

      

so that it v

now holds the value represented by my fraction. How do I do this in C ++?

+1


a source to share


5 answers


One way to do this is to define a conversion operator:

struct fraction
{
  size_t numerator;
  size_t denominator;

  operator float() const
  {
     return ((float)numerator)/denominator;
  }
};

      

Most people would prefer not to define an implicit conversion operator as a matter of style. This is because transformation operators tend to operate behind the scenes and it can be difficult to determine which transformations are in use.



struct fraction
{
  size_t numerator;
  size_t denominator;

  float as_float() const
  {
     return ((float)numerator)/denominator;
  }
};

      

In this version, you call a method as_float

to get the same result.

+7


a source


Assignment operators and conversion constructors are for initializing objects of your class from objects of other classes. Instead, you need a way to initialize an object of some other type with an object of your class. This is a conversion operator for:



struct fraction {
     //other members here...
     operator double() const { return (double)numerator / denominator;}
     //other members here...
};

      

+3


a source


You can use the double operator to convert:

struct fraction
{
     operator double() const
      {
         //remember to check for  denominator to 0
          return (double)numerator/denominator;
      }
};

      

+2


a source


operator=

has nothing to do with it, rather you want to add to your struct

public operator double

something like:

operator double() {
  return ((double) numerator))/denominator;
}

      

+1


a source


With so much of the code, it would be a compiler error because the compiler cannot convert the structure fraction to a double. If you want to provide a transformation, you need to define operator double()

which one will be used by the compiler for that transformation.

0


a source







All Articles