reinterpret_cast的C等价物是多少?

来自C ++的reinterpret_cast的C等价物是多少?

 int *foo; float *bar; // c++ style: foo = reinterpret_cast< int * >(bar); // c style: foo = (int *)(bar); 

C样式的强制转换看起来像括号中的类型名称:

 void *p = NULL; int i = (int)p; // now i is most likely 0 

显然,演员阵容有更好的用途,但这是基本语法。

它不存在,因为reinterpret_cast不能改变[constness] [3]。 例如,

 int main() { const unsigned int d = 5; int *g=reinterpret_cast< int* >( &d ); (void)g; } 

会产生错误:

dk.cpp:在函数’int main()’中:
dk.cpp:5:41:错误:从’const unsigned int *’类型reinterpret_cast到’int *’类型转换掉限定符

C风格的演员是:

 int* two = ...; pointerToOne* one = (pointerToOne*)two; 

如果你可以获取值的地址,一种方法是将指针转换为指向不同类型的指针,然后取消引用指针。

例如,float-to-int转换:

 int main() { float f = 1.0f; printf ("f is %f\n", f); printf ("(int) f is %d\n", (int)f); printf ("f as an unsigned int:%x\n", *(unsigned int *)&f); } 

输出:

 f is 1.000000 (int) f is 1 f as an unsigned int:3f800000 

请注意,这可能无法保证符合C标准。 无论如何,你不能使用reinterpret_cast从float转换为int,但对于支持的类型(例如,在不同的指针类型之间)它将类似。

无论如何,让我们确认上面的输出是有意义的。

http://en.wikipedia.org/wiki/Single_precision_floating-point_format#IEEE_754_single-precision_binary_floating-point_format:_binary32

二进制的最后一个答案:

0011 1111 1000 0000 0000 0000 0000 0000

这是IEEE-754浮点格式:符号位为0,后跟8位指数(011 1111 1),后跟23位尾数(全零)。

要解释指数,减去127:01111111b = 127,并且127 – 127 = 0.指数为0。

要解释尾数,请在1后跟小数点后写入:1.00000000000000000000000(23个零)。 这是十进制的1。

因此,正如我们预期的那样,由hex 3f800000表示的值是1 * 2 ^ 0 = 1。

您可以像在任何其他类型中一样在C中自由地转换指针类型。

完成:

 void *foo; some_custom_t *bar; other_custom_t *baz; /* Initialization... */ foo = (void *)bar; bar = (some_custom_t *)baz; baz = (other_custom_t *)foo; 

对于c的REINTERPRET运算符怎么样:

 #define REINTERPRET(new_type, var) ( * ( (new_type *) & var ) ) 

我不喜欢说“reinterpret_cast”,因为强制转换意味着转换(在c中),而重新解释意味着相反:没有转换。