【问题标题】:unsigned int vs unsigned long both are 32bit but I can't intermix them without casting... why?unsigned int 和 unsigned long 都是 32 位的,但我不能在不强制转换的情况下混合它们......为什么?
【发布时间】:2019-06-14 17:39:09
【问题描述】:

我的电脑显示sizeof unsigned long 和unsigned int 是一样的。

但是,当将参数传递给方法时……更具体地说是指针……我必须将unsigned int 重新转换为unsigned long。否则生成错误Compiler Error C2664":'function' : cannot convert argument n from 'type1' to 'type2'

为什么?

【问题讨论】:

  • 因为它们是不同的类型。就像struct Foo { int x; } 和struct Bar { int x; } 是不同的类型,即使它们具有相同的布局。
  • 它们是不同的类型,大小也由实现定义see here
  • 隐式转换不能通过指针进行。
  • 产生该错误的代码示例将有助于使这个问题在未来对其他人更有用。

标签: c++ visual-studio-2012


【解决方案1】:

就编译器而言,它们是完全不相关的类型。传递 any 类型的指针,但参数期望的指针除外。

但即使编译器已经认识到这种类型的指针转​​换是可能的并为你做,这就是为什么那会很糟糕......

C++ 已经存在了足够长的时间,以至于int 和long 随着新 CPU 架构的出现和消失而改变了大小。 int 和 long 的大小取决于您正在使用的编译器和平台,因此,将 int* 转换为 long* (反之亦然)可以引导您直接进入 all sorts of problems 如果它们是 不大小相同。

根据C++ standard,这些是int 和long 在各种平台上的大小:

type | C++ standard | LP32 | ILP32 | LLP64 | LP64
-------------------------------------------------
int  | at least 16  | 16   | 32    | 32    | 32      bits
long | at least 32  | 32   | 32    | 32    | 64      bits

只有使用 ILP32 和 LLP64,您才能安全地假设 int 和 long 大小相同,但在编译器中支持该假设将允许您编写无法在其他平台上安全编译或运行的代码。

最后,如果您需要保证整数的大小在所有平台上都相同,那么您可以#include <cstdint> 并使用int16_t、uint16_t、int32_t 等类型。这些已修复-width 整数可用于支持 C++11 及更高版本的编译器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-15
    • 2013-08-01
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多