简体   繁体   中英

How to change type of int to double in c++

Is there any way to initialize a variable as a general number type or int and then change its type to double for example?

TYPE x = 4;
// commands changing its type
here it(variable x) became double.

I know it is weird.

The variable has to have the same name.

No. C++ is a statically typed languages. The type is fixed when the variable is declared.

You could kind of do what you describe using a union, but great care is required, eg

union DoubleInt
{
  int i;
  double d;
};

DoubleInt X;
X.i = 4;

// ... whatever

X.d = X.i;
X.d += 0.25;

But unions are really only a sensible option where you're desperate to bit pack. You could also create a class that can behave as either a double or int but, really, what you're talking about doing doesn't sound like you're thinking in a C++ way.

Finally, boost::variant might do what you want?

Though it is not possible to change the type of a variable, you can define a type capable of representing variables of various types. This is generally called a variant . Go and get Boost.Variant which allows you to write code like this:

boost::variant<int, double> t_either_int_or_double;

t_either_int_or_double = 1;

// now it is "int"
assert(boost::get<int>(t_either_int_or_double);

t_either_int_or_double = 1.0;

// now it is "double"
assert(boost::get<double>(t_either_int_or_double);

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