错误:从“..”强制转换到“unsigned int”将丢失精度[-fpermission]
error: cast from ‘...’ to ‘unsigned int’ loses precision [-fpermissive]
在我的代码中,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);
相关文章:
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 主.cpp:18:20:错误:从"int*"转换为"int"会失去精度 [-fa
- 如何解决隐式转换丢失整数精度:'size_t'(又名"无符号长")到'int'警告?
- int 到浮点转换的精度损失
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- f 是指向函数的指针,该函数采用 int,并返回指向不带任何内容并返回双精度的函数的指针
- 将双精度值分配给 int 数组时的类型转换
- 标准::p空气<矢量、双精度的初始值设定项列表<int>>
- 如果我在 C++ 中为 int 提供双精度,输入缓冲区中存储了什么?
- 是否应该避免这种从 int 到双精度的静态转换?
- 在 C++ 中将 int 转换为双精度
- 将大双精度转换为无符号 int 期间堆栈损坏
- 将 int 转换为双精度以执行 std::complex <double>的"*"操作
- C++错误:从“int*”转换为“int”会失去精度
- 从 double* 转换为 int 会失去精度
- 隐式转换会丢失整数精度:'long' 到 'int'
- C++ 将 int 转换为双精度不起作用
- 在算术表达式中,双精度会隐式转换为无符号 int 吗?
- C++:使用一对(cpp_int,int)整数作为无序映射中的键(其中cpp_int是boost多精度整数)