相关疑难解决方法(0)

何时使用reinterpret_cast?

我对reinterpret_castvs 的适用性感到困惑static_cast.从我读到的一般规则是使用静态转换,当类型可以在编译时解释,因此这个词static.这是C++编译器内部用于隐式转换的转换.

reinterpret_casts适用于两种情况,将整数类型转换为指针类型,反之亦然,或将一种指针类型转换为另一种指针类型.我得到的一般想法是不可移植的,应该避免.

我有点困惑的地方是我需要的一种用法,我从C调用C++并且C代码需要保持C++对象,所以基本上它拥有一个void*.什么演员应该用于在void *类型和类型之间进行转换?

我看过两者的用法static_castreinterpret_cast?虽然从我读过的内容看起来似乎static更好,因为演员阵容可以在编译时发生?虽然它说用于reinterpret_cast从一种指针类型转换为另一种指针类型?

c++ casting

432
推荐指数
6
解决办法
31万
查看次数

为什么`reinterpret_cast`不像C++标准那样表现?

在入口处reinterpret_cast,cppref说:

可以将积分,枚举,指针或指向成员类型的表达式转换为其自己的类型.结果值与表达式的值相同.(自C++ 11以来)

但是,以下代码无法编译(clang 5.0 with -std=c++1z):

enum class A : int {};

int main()
{
    A a{ 0 };
    reinterpret_cast<int>(a); // error : reinterpret_cast from 'A' to 'int' is not allowed
}
Run Code Online (Sandbox Code Playgroud)

为什么不像reinterpret_castC++标准那样表现?

c++ standards casting type-conversion c++11

-1
推荐指数
1
解决办法
70
查看次数

标签 统计

c++ ×2

casting ×2

c++11 ×1

standards ×1

type-conversion ×1