c – reinterpret_cast错误为枚举
为什么我不能使用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); } 解决方法
这是一个常见的误解.可以使用reinterpret_cast执行的转换在标准的5.2.10中明确列出. int-to-enum和enum-to-int转换不在列表中: >整数类型的指针,只要整数大到足以容纳它 reinterpret_cast通常用于告诉编译器:嘿,我知道你认为这个内存区域是T,但我想让你把它解释为一个U(其中T和U是不相关的类型). 还值得注意的是,reinterpret_cast可以对位有影响:
C风格的演员总是奏效,因为它包含了static_cast的尝试. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |