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

C++ C++;:为什么某些函数必须放在if语句中?,c++,function,pointers,position,cursor-position,C++,Function,Pointers,Position,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

我将参考以下答案:

工作守则:

    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;
    }
HWND-HWND;
p点;
if(GetCursorPos&p))
{
//光标现在在p.x和p.y中的位置
}
if(屏幕到客户(hwnd和p))
{
//p、 x和p.y现在相对于hwnd的客户区域

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

   if(functionReturningSuccess(params))
   {
      //assume the operation succeeded
   }
   else
   {
      //report error
   }
if(GetCursorPos&p)和ScreenToClient(hwnd,&p))
非常有害,但却异常优雅

由于
&
运算符的短循环性质,只有在
GetCursorPos(&p)
成功运行(即返回转换为
true的内容)时才会调用
ScreenToClient(hwnd,&p)
)。后者如果成功,也会将
p
设置为对后续
ScreenToClient
调用有效的值

只有当两个函数都成功时,才会运行封闭的
if


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

这如何回答为什么
if(GetCursorPos&p)和&ScreenToClient(hwnd&p))
如果它不是两个独立的if块,则会崩溃?@NathanOliver问题中有许多问题。这似乎是对另一个问题的回答,而不是您所指的问题。我怀疑您遇到了堆栈损坏之类的问题。重新更改代码很容易隐藏或暴露错误行为。在显示的代码中,程序should不会崩溃,看起来问题出在其他地方当然会崩溃,因为hwnd没有定义。
hwnd
没有定义,你确定这是完整的代码吗?不,我一点也不确定。定义hwnd甚至没有显示在我链接的答案中,但我把它放在那里并编译。然而,正如OP所说,
if(GetCursorPos(&p)&&ScreenToClient(hwnd,&p))
在他单击窗口时仍会崩溃
    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(functionReturningSuccess(params))
   {
      //assume the operation succeeded
   }
   else
   {
      //report error
   }