如何将自定义 class 指针转换为 unsigned int

How to convert custom class pointer to unsigned int

我需要将自定义 class 指针类型转换为无符号整型值。这是我累了。

Class A{
};

int main()
{
A* a = foo();
unsigned int handler = reinterpret_cast<unsigned int>(a);
return 0;
}

它给出了警告 warning C4302: 'reinterpret_cast': truncation from 'A *' to 'unsigned int'

用 C++ 方式克服这个问题的正确方法是什么

该错误可能暗示您正在编译为 64 位目标,在这种情况下,指针为 64 位,reinterpret_cast 为 int 意味着截断(因为 int 最多为 32 位)。

不确定你要用处理程序做什么,但更安全的方法是转换为 uintptr_t 如果 c++11 可用。

http://en.cppreference.com/w/cpp/types/integer

加上 <cstdint>,应该是这样的,

uintptr_t handler = reinterpret_cast<uintptr_t>(a);