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 ++?
a source to share
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.
a source to share
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...
};
a source to share