为什么不restrpret_cast编译? [英] Why doesn't this reinterpret_cast compile?

查看:124
本文介绍了为什么不restrpret_cast编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道reinterpret_cast是危险的,我只是这样做来测试它。我有以下代码:

I understand that reinterpret_cast is dangerous, I'm just doing this to test it. I have the following code:

int x = 0;
double y = reinterpret_cast<double>(x);

当我试图编译程序时,它给我一个错误,说

When I try to compile the program, it gives me an error saying

invalid cast from type 'float' to type 'double

发生了什么事?我认为reinterpret_cast是流氓演员,你可以用来将苹果转换为潜艇,为什么不是这个简单的铸造编译?

What's going on? I thought reinterpret_cast was the rogue cast that you could use to convert apples to submarines, why won't this simple cast compile?

推荐答案

通过将y赋值给转换返回的值,您不会真正转换值 x ,您正在转换它。也就是说, y 没有指向 x ,并假装它指向一个浮点。转换构造类型 float 的新值,并从 x 分配值。有几种方法可以在C ++中进行这种转换,其中有:

By assigning y to the value returned by the cast you're not really casting the value x, you're converting it. That is, y doesn't point to x and pretend that it points to a float. Conversion constructs a new value of type float and assigns it the value from x. There are several ways to do this conversion in C++, among them:

int main()
{
    int x = 42;
    float f = static_cast<float>(x);
    float f2 = (float)x;
    float f3 = float(x);
    float f4 = x;
    return 0;
}

唯一真正的区别是最后一个(隐式转换)编译器诊断在更高的警告级别。但是它们在功能上都是一样的 - 并且在很多情况下实际上是相同的东西,如同一个机器代码。

The only real difference being the last one (an implicit conversion) will generate a compiler diagnostic on higher warning levels. But they all do functionally the same thing -- and in many case actually the same thing, as in the same machine code.

现在if你真的想假装 x 是一个float,那么你真的想通过这样做来转换 x

Now if you really do want to pretend that x is a float, then you really do want to cast x, by doing this:

#include <iostream>
using namespace std;

int main()
{
    int x = 42;
    float* pf = reinterpret_cast<float*>(&x);
    (*pf)++;
    cout << *pf;
    return 0;
}

你可以看到这是多么危险。事实上,我在我的机器上运行这个输出是 1 ,这绝对不是42 + 1。

You can see how dangerous this is. In fact, the output when I run this on my machine is 1, which is decidedly not 42+1.

这篇关于为什么不restrpret_cast编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆