简体   繁体   English

如何在C ++中将int的类型更改为double

[英]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? 有什么方法可以将变量初始化为通用数字类型或int,然后将其类型更改为例如double?

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. 否。C++是一种静态类型的语言。 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. 您还可以创建一个可以充当double或int的类,但实际上,您正在谈论的事情听起来并不像您在以C ++的方式思考。

Finally, boost::variant might do what you want? 最后, boost :: variant可能会做您想要的?

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 ,它允许您编写如下代码:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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