如何将自定义类指针转换为无符号int

How to convert custom class pointer to unsigned int

本文关键字:转换 无符号 int 指针 自定义      更新时间:2023-10-16

我需要键入指向无符号int值的强制转换自定义类指针。这是我累的东西。

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位的,重新解释到int意味着截断(因为int是atmost 32位)。

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

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

如果包含<cstdint>,它应该类似于

uintptr_t handler = reinterpret_cast<uintptr_t>(a);