简体   繁体   中英

How to convert a user defined type to primitive type?

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!!

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

You mean you want to do this

Complex c;
double d =  c; ?

You can write a conversion operator for that purpose

struct Complex{
   double double_val;

   operator double() const {
       return double_val;
   }
};

The rub with a Complex class is that complex numbers are a superset of real numbers, ie while all real numbers are also complex numbers, not all complex numbers are real numbers.

So while, as others pointed out, you need to define a typecast operator in Complex for double , the real work is what you put into that function. The safest thing would be to throw an exception if the number isn't real:

#include <exception>

struct Complex
{
    double real;
    double imag;

    Complex(double real_, double imag_ = 0.0): real(real_), imag(imag_) {)

    // ...

    class not_real: public exception
    {
        virtual const char* what() const throw()
        {
            return "cannot cast non-real complex number to double";
        }
    };

    operator double() const {
        if(imag != 0.0)
            throw not_real();
        return real;
    }
};

operator double is what you need

class Complex
{
   operator double() const {....}
}

You can create a custom cast operator: - http://msdn.microsoft.com/en-us/library/ts48df3y%28v=VS.100%29.aspx - Operator-Overloading/doublecastoperator.htm">http://www.java2s.com/Tutorial/Cpp/0200_Operator-Overloading/doublecastoperator.htm

So your code would look something like this (within your Complex class): operator double () { return /* whatever you want to do to the complex */ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM