Let's say we have a class called Complex
which represents a complex number.
I want to convert this object to a double
object.
The other way around i can do by implementing a copy ctor in Complex:Complex(const double &d);
However, i can't implement i copy ctor in double which will receive a Complex.
How do i do this? I know there is a way with operator overloading, but i couldn't find how.
Eventually i want the this line will compile:Complex c;
(double)c;
Thanks!!
C++ Now, this function converts a user-defined data type to a primitive data type. For Example, the operator double() converts a class object to type double, the operator int() converts a class type object to type int, and so on.
You convert an Object variable to another data type by using a conversion keyword such as CType Function.
For more information, see Standard Conversions. User-defined conversions perform conversions between user-defined types, or between user-defined types and built-in types. You can implement them as Conversion constructors or as Conversion functions.
There are two types of user-defined conversions: Conversion constructors and conversion functions.
Implement a conversion operator on your Complex class:
class Complex
{
// ...
operator double() const
{
double ret = // magic happens here
return ret;
}
};
If for whatever reason you don't want to muck about with this, you can provide a global conversion function:
double convert_to_double(const Complex& rhs)
{
double ret = // magic happens
return ret;
}
The proper way of doing this is adding a conversion operator to your class.
class myclass {
public:
operator double() const
{
return _mydouble;
}
...
};
and used like this:
myclass c;
double d = c; // invokes operator double
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With