Reputation: 44458
Forgive what might seem to some to be a very simple question, but I have this use case in mind:
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 statements like:
fraction f(3,5);
...
double v = f;
to have v
now hold the value represented by my fraction.
How would I do this in C++?
Upvotes: 1
Views: 809
Reputation: 881705
operator=
has nothing to do with it, rather you want to add to your struct
a public operator double
something like:
operator double() {
return ((double) numerator))/denominator;
}
Upvotes: 1
Reputation: 35460
You can use the operator double to convert:
struct fraction
{
operator double() const
{
//remember to check for denominator to 0
return (double)numerator/denominator;
}
};
Upvotes: 2
Reputation: 73443
With that much of code it will be compiler error as the compiler doesn't how to convert struct fraction into a double. If you want to provide the conversion then you have to define the operator double()
which will be used by the compiler for this conversion.
Upvotes: 0
Reputation: 170489
Assignment operators and conversion constructors are for initializing objects of your class from objects of other classes. You instead need a way to initialize an object of some other type with an object of your class. That's what a conversion operator is for:
struct fraction {
//other members here...
operator double() const { return (double)numerator / denominator;}
//other members here...
};
Upvotes: 3
Reputation: 135295
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 will prefer not to define an implicit conversion operator as a matter of style. This is because conversion operators tend to act "behind the scenes" and it can be difficult to tell which conversions are being used.
struct fraction
{
size_t numerator;
size_t denominator;
float as_float() const
{
return ((float)numerator)/denominator;
}
};
In this version, you would call the as_float
method to get the same result.
Upvotes: 7