【问题标题】:Confused about type conversion in C++对 C++ 中的类型转换感到困惑
【发布时间】:2011-02-02 10:42:57
【问题描述】:

在 C++ 中,以下几行让我感到困惑:

int temp = (int)(0×00);

int temp = (0×00int);

这两行有什么区别?

【问题讨论】:

  • 你从哪里得到的代码?
  • 你到底为什么会有这个疑问?int temp = (0×00int);- 为什么????
  • 我今天学到的另一件事。虽然从技术上讲,您可以使用“(int)”进行类型转换,但 C++ 的方式是编写“static_cast”

标签: c++ types type-conversion


【解决方案1】:

两者都无效,因为您使用的是× 而不是x:

test.cpp:6: error: stray '\215' in program
test.cpp:6: error: expected primary-expression before "int"
test.cpp:6: error: expected `)' before "int"

但即使解决了这个问题,第二个仍然不是有效的 C++,因为你不能写 0x00int:

test.cpp:6:13: invalid suffix "int" on integer constant

第一个是有效的(在将× 更改为x 之后)并将值0 分配给temp。不过,这里不需要强制转换——你不需要仅仅因为常量是用十六进制编写的。你可以写:

int temp = 0x00;

【讨论】:

  • 为了更清楚一点,第二条语句告诉编译器您要为“temp”分配一些值。使用“0x”前缀告诉它这个值将以十六进制表示。十六进制数的有效字符为:1234567890abcdef。现在你必须在你的陈述中看到问题。
【解决方案2】:

第一个将0分配给temp

秒会导致编译错误。

当扫描仪看到 0× 时,它期望后面跟着十六进制数字,但是当它看到 i 这不是一个有效的十六进制数字时,它会给出错误。

【讨论】:

    【解决方案3】:

    第一个将十六进制值0x00作为一个int,并用它来初始化变量temp。

    第二个是编译错误。

    【讨论】:

      【解决方案4】:

      第一行是有效的 C++,基本上等同于

      int temp = 0; 
      

      而第二个将无法编译(正如这里的每个人所建议的那样)。

      【讨论】:

        【解决方案5】:

        投射方式:

        int temp = (int)0x00;  // Standard C-style cast
        int temp = int(0x00);  // Function-style cast
        int temp = static_cast<int>(0x00);  // C++ style cast, which is clearer and safer
        int temp = reinterpret_cast<int>("Zero"); // Big-red-flag style unsafe cast
        

        static_cast 和 reinterpret_cast 的有趣之处在于,好的编译器会在您使用错误时发出警告,至少在某些情况下是这样。

        例如,如果您尝试将 0x00 重新解释为 int,Visual Studio 2005 将引发错误,因为该转换以安全的方式可用。实际消息是:“转换是有效的标准转换,可以隐式执行,也可以使用 static_cast、C 样式转换或函数样式转换”。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-10-14
          • 2021-11-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-30
          • 1970-01-01
          相关资源
          最近更新 更多