【问题标题】:C++/SDL Overwriting an array some how?C++/SDL 如何覆盖数组?
【发布时间】:2017-08-23 22:20:43
【问题描述】:

我正在为一个项目创建一个游戏引擎,并使用 SDL 进行输入和其他内容。

我有这样的事情:

class CInput
{
public:
    CInput();

    Rect MousePosition      = Rect(0, 0);
    Rect MouseDeltaPosition = Rect(0, 0);

    bool GetMouseButton(int button);

    bool Process();

private:
    bool _mouseButtons[5];
};

bool CInput::GetMouseButton(int button)
{
    return _mouseButtons[button - 1];
}

rect结构是这样的:

struct Rect
{
    int x, y;

    Rect(int x, int y) : x(x), y(y) {};
};

我正在记录鼠标按钮和移动以用于任何实际用途,但似乎当我设置 mouseposition/mousedeltaposition 时它“溢出”到 _mouseButtons 数组上?

这是我的输入捕获:

while (SDL_PollEvent(&event))
{
    switch (event.type)
    {
    case SDL_MOUSEMOTION:
        MousePosition      = Rect(event.motion.x, event.motion.y);
        MouseDeltaPosition = Rect(event.motion.xrel, event.motion.yrel);

        break;

    case SDL_MOUSEBUTTONDOWN:
        _mouseButtons[event.button.button - 1] = true;
        break;
    case SDL_MOUSEBUTTONUP:
        _mouseButtons[event.button.button - 1] = false;
        break;

    case SDL_QUIT:
        return 0;
    }
}

在测试期间,即使没有人按下按钮,_mouseButton 数组也可以填充 255。

编辑---

imgur

这只是简单地做:Input.GetMouseButton(0) 当鼠标在某个位置时返回 255

!!!我已经缩小了问题的范围,它似乎发生在 DeltaMousePosition.y 为负数时,因为鼠标相对于窗口向上移动!可能是问题

【问题讨论】:

  • 它可能 溢出,因为你对编译器撒谎说变量是 const。
  • 这是最小的,它是完整的问题......
  • 我们很难编译和测试..
  • 从字面上看,除了函数名之外,我没有什么能告诉你的了……

标签: c++ arrays struct sdl


【解决方案1】:
const Rect MousePosition      = Rect(0, 0);
// ...
*(Rect*)(&MousePosition)      = Rect(event.motion.x, event.motion.y);

你告诉编译器 MousePosition 是 const。它不是引用也不是指针,所以编译器肯定知道MousePosition.xMousePosition.y 永远不会改变,这意味着它们是0。从现在到永远,他们将是0

如果编译器按照我期望的方式优化您的代码,它将完全删除 MousePositionMouseDeltaPosition,并用文字0,这就是为什么你要写在你的数组中。

TLDR:不要对编译器撒谎。如果您正在写入变量,请不要将其设为 const 并抛弃 const 性。

编辑:

这是简单的做法:当鼠标在某个位置时,Input.GetMouseButton(0) 返回 255

好吧,看看那个函数:

bool CInput::GetMouseButton(int button)
{
    return _mouseButtons[button - 1];
}

0 - 1-1,因此从 _mouseButtons[-1] 读取数据会从其他地方读取数据。未定义的行为。

【讨论】:

  • 我现在已经删除了 const,但问题仍然存在。更新帖子
  • 枚举从1开始,所以鼠标键没有0
  • @ReeceWard “鼠标按钮没有 0”但有问题你说你确实使用 0 作为测试用例。其中之一是错误的。如果您确实使用 [1;5] 范围内的值,那么问题不在呈现的代码中。
猜你喜欢
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多