简体   繁体   English

使用指针C ++进行转换

[英]Casting with pointer C++

Say I have an object: 说我有一个对象:

void *tmpValue;

and say I know that tmpValue points to a double. 说我知道tmpValue指向双精度值。 A way to cast this into a double is to do the following: 将其转换为双精度的一种方法是执行以下操作:

double* dblPtr = (double*) tmpValue;
double dbl = *dblPtr;

But why does a direct casting from void* to double not work? 但是,为什么从void *直接转换为double无效?

double dbl = (double) tmpValue; //error: "cannot convert from 'void*' to 'double'

Thanks in advance. 提前致谢。

Interpreting a pointer (a memory address) as a floating-point value is not a sensible operation, and it probably fails on your platform because void * and double are not even the same size. 将指针(内存地址)解释为浮点值不是明智的操作,并且在您的平台上可能会失败,因为void *double的大小甚至都不相同。

What you want to do is interpret the pointer as double * and dereference that double * pointer, as in your second code snippet. 您想要做的就是将指针解释为double *并取消引用double *指针,如第二个代码段所示。

You can do this in one line: 您可以在一行中完成此操作:

double dbl = *(double *)tmpValue;

But, hey, this is C++. 但是,嘿,这是C ++。 Better to do 最好做

double dbl = *static_cast<double *>(tmpValue);

You can't cast from a pointer type to double. 您不能从指针类型强制转换为double。 Recall that pointer type is essentially a memory address (typically 4 bytes containing location information of the data on the memory). 回想一下,指针类型实质上是一个内存地址(通常为4个字节,其中包含数据在内存中的位置信息)。 Hence you can cast pointer type to integer, but casting to double wouldn't make sense. 因此,您可以将指针类型强制转换为整数,但是强制转换为double则没有意义。

When you cast the void* pointer into double* pointer type, you are essentially saying "this is now an address of a double rather than an address of void*" 当您将void *指针转换为double *指针类型时,您实际上是在说“这现在是double的地址,而不是void *的地址”

If you want to get the value as double in one liner nevertheless, you can do 但是,如果您希望将价值提高一倍,就可以做到

double dbl = *( (double*) tmpValue );
double dbl = *(double*)tmpValue

取消引用指针并强制转换值

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

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