C++:为什么有些函数必须放在 if 语句中?

C++: Why must some functions be placed in if statements?

我将参考这个答案:Get current cursor position

工作代码:

    HWND hwnd;
    POINT p;
    if (GetCursorPos(&p))
    {
        //cursor position now in p.x and p.y

    }
    if (ScreenToClient(hwnd, &p))
    {
        //p.x and p.y are now relative to hwnd's client area
        cout << p.x << p.y;
    }

这可以编译,但是当我点击 window:

时崩溃
    HWND hwnd;
    POINT p;
    if (GetCursorPos(&p) && ScreenToClient(hwnd, &p))
    {
        //cursor position now in p.x and p.y
        cout << p.x << p.y;
    }

这也可以编译,但是当我点击 window:

时崩溃
    HWND hwnd;
    POINT p;
    GetCursorPos(&p);
    if (ScreenToClient(hwnd, &p))
    {
        //cursor position now in p.x and p.y
        cout << p.x << p.y;
    }

为什么?这些功能有什么不寻常之处吗?

跟涉及到指针有关系吗?

将这些函数放在 if 语句中如何改变它们 运行 的方式?

它不会改变功能 运行 的方式。许多函数 return 一个布尔值,指示操作是否成功。通过将函数调用包含在 if 中,您将自动检查操作是否成功。

   if(functionReturningSuccess(params))
   {
      //assume the operation succeeded
   }
   else
   {
      //report error
   }

if (GetCursorPos(&p) && ScreenToClient(hwnd, &p)) 相当有害,但 st运行 非常优雅。

由于 && 运算符的 短路 性质,只有 GetCursorPos(&p) 成功运行时才会调用 ScreenToClient(hwnd, &p)(即returns 转换为 true 的东西)。后者,如果成功,也恰好将 p 设置为对后续 ScreenToClient 调用有效的内容。

如果两个函数都成功,则封闭的if块只有运行。

您的崩溃很可能是由于您的 hwnd 未初始化。