c++ - 转换具有不同容量的整数

标签 c++

我有以下代码:

// ---- third party library code ----
struct Point { int16_t x, y; };
void third_party_library__getPoint(Point*);
void third_party_library__setPoint(const Point*);

// ---- my library code ----
void move_point(int dx, int dy)
{
    Point pt;
    third_party_library__getPoint(&pt);
    pt.x += dx;
    pt.y += dy;
    third_party_library__setPoint(&pt);
}

专线pt.x += dx;产生警告
conversion from 'int' to 'int16_t', possible loss of data

我该怎么办?

  1. 禁用这些行的警告
  2. 将警告源移至接口(interface):make dxdy int16_t,所以谁会用move_point函数将处理这个问题。
  3. 刚投dxdy到 int16_t。
  4. 添加assert(dx <= 0x7FFF && dx >= -0x8000 && "too large 'dx' value")并希望它会在我运行调试版本时命中。

最佳答案

您应该将 dx 和 dy 设置为 int16_t,如果您强制转换它们,您只是将其隐藏,使用您的代码的人将不会看到这些警告并且不会意识到问题所在。因此,让另一方的人处理警告,至少他们当时对功能有把握。

关于c++ - 转换具有不同容量的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4566210/

相关文章:

c++ - 我需要一个 S4s 服务器的 C++ 接口(interface)

c++ - 如何创建具有多类的 MFC 扩展 dll?

c++无法理解使用智能指针的非常基本的概念

c++ - 指向继承类实例的指针作为函数参数

c++ - 将所有 C++ std::vector 值递增一个常数值

c++ - 为什么 ostream_iterator 没有按预期工作?

c++ - C++ 中 Delete 的行为

c++ - 在 C++ 中递增未初始化的 int 安全吗?

c++ - C++ 中是否存在类型的 constexpr 排序?

c++ - 如何仅在所有先前条件都为假时才执行 block ,并在其中一个条件为真时执行特定 block ?