代码之家  ›  专栏  ›  技术社区  ›  Venkat

关于C++中类型转换的困惑

  •  0
  • Venkat  · 技术社区  · 16 年前

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

    这两条线有什么区别?

    5 回复  |  直到 16 年前
        1
  •  12
  •   Mark Byers    16 年前

    × 而不是 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"
    

    0x00int :

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

    int temp = 0x00;
    
        2
  •  3
  •   Joris Timmermans    16 年前

    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
    

    静态\u cast和重新解释\u cast的有趣之处在于,一个好的编译器会在错误使用它们时发出警告,至少在某些情况下是这样。

    例如,如果您尝试将\u cast 0x00重新解释为int,VisualStudio2005将抛出一个错误,因为这种转换是安全的。实际的消息是:“转换是一个有效的标准转换,可以隐式执行,也可以使用静态类型转换、C样式转换或函数样式转换”。

        3
  •  1
  •   codaddict    16 年前

    第一个将分配 0 temp

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

        4
  •  1
  •   Daniel Daranas    16 年前

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

        5
  •  0
  •   Buhake Sindi Tesnep    16 年前

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

    int temp = 0; 
    

    而第二个将无法编译(这里的每个人都建议)。