作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
为什么我不能对这样的转换使用 reinterpret_cast 运算符?
enum Foo { bar, baz };
void foo(Foo)
{
}
int main()
{
// foo(0); // error: invalid conversion from 'int' to 'Foo'
// foo(reinterpret_cast<Foo>(0)); // error: invalid cast from type 'int' to type 'Foo'
foo(static_cast<Foo>(0));
foo((Foo)0);
}
最佳答案
I think that
reinterpret_cast
can be use for all types of casts, because it's force any type casts to another type with all side-effects of this conversion.
这是一个常见的误解。可以使用 reinterpret_cast
执行的转换在标准的 5.2.10 中明确列出。 int
-to-enum
和 enum
-to-int
转换不在列表中:
nullptr_t
到整数枚举
指针nullptr_t
到其他指针类型T1
和
的情况下,
T1
的指向成员的指针指向 T2
的不同指向成员的指针T2
是对象或函数reinterpret_cast
通常用于告诉编译器:嘿,我知道你认为这个内存区域是一个 T
,但我希望你将它解释为U
(其中 T
和 U
是不相关的类型)。
还值得注意的是,reinterpret_cast
会对位产生影响:
5.2.10.3
[ Note: The mapping performed by reinterpret_cast might, or might not, produce a representation dif- ferent from the original value. — end note ]
C 风格的转换总是有效的,因为它在尝试中包含了 static_cast
。
关于c++ - 枚举的 reinterpret_cast 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12228562/
我是一名优秀的程序员,十分优秀!