错误:从“..”强制转换到“unsigned int”将丢失精度[-fpermission]

error: cast from ‘...’ to ‘unsigned int’ loses precision [-fpermissive]

本文关键字:精度 int -fpermission 错误 转换 unsigned      更新时间:2023-10-16

在我的代码中,Graph是一个具有成员node的类,这是一个结构。当我做时

unsigned int id  = ((unsigned int)n - (unsigned int)_nodes) / sizeof(Graph::node); 

我得到以下错误(在64位Linux上编译):

error: cast from ‘Graph::node* {aka Graph::node_st*}’ to ‘unsigned int’ loses precision [-fpermissive]

在谷歌上搜索并找到了一个类似的问题,但在我看来,答案在这里不适用(注意,我想得到物体的大小,但不想得到它本身)。

提前感谢您的任何建议!

如果n_nodes指向Graph::node,即它们的类型为Graph::node *(从错误消息来看似乎是这样),并且如果您希望根据Graph::node元素的数量来计算两者之间的"距离",您可以执行:

unsigned int id = n - _nodes;

在C和C++中,指针算术将导致元素数量(而不是字节数量)的差异。

为了便于移植,n_nodes都必须指向Graph::node值的连续块,并且n应该在_nodes之后。如果可以获得负差异,则可以使用ptrdiff_t类型而不是unsigned int

SO文章中的第一个答案提供了一个适合您的答案。

使用

intptr_t id  = ((intptr_t)n - (intptr_t)_nodes) / sizeof(Graph::node);