这个&算子是什么意思? [英] What does this & operator mean here?

查看:217
本文介绍了这个&算子是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在qt中阅读了一些关于openGL的教程。
其中一个鼠标事件插槽中有此代码:

I was reading some tutorial about openGL in qt. One of the mouse event slot has this code in it:

if (event->buttons() & Qt::LeftButton) {    
    rotationX += 180 * dy;
    rotationY += 180 * dx;
    updateGL();
}

运算符在if语句中执行?
与==完全相同

what does the & operator do in the if statement? is it exactly the same as == ?

推荐答案

它不等于 == 。它是位与运算符。该表达式的作用是,它从 event-> buttons()按位与的返回值与表示的值 Qt :: LeftButton

It is not the same as ==. It is bitwise AND operator. What the expression does is that it takes the return value from event->buttons() and bitwise AND's it with the value represented by Qt::LeftButton. If the resulting value is non-zero the block is being executed.

实质上,它会检查 Qt :: LeftButton 是否指定的按钮, / code>被按下。

In essence, it checks if the button specified by Qt::LeftButton is held down.

这里使用位和AND 称为位掩码。这意味着 event-> buttons()的返回值只是一个值,它的位代表不同种类的状态。这里的& -operator做的是检查是否有某些位(由 Qt :: LeftButton 表示)被设置(1)或未设置 event-> buttons()返回的值。

The reason why the bitwise AND operator is used here is something called a bitmask. What it means is that the return value of event->buttons() is just a value which has it's bits represent different kinds of states. What is done with the &-operator here is that it checks if certain bits(denoted by Qt::LeftButton) are being set(1) or unset(0) in the value returned by event->buttons(). The return value is zero if no tested bit is set, and non-zero, if at least one of the tested bits is set.

如果没有设置测试位,则返回值为零,如果设置了至少一个测试位,返回值为非零。可以在这里找到:关于Bitwise操作的维基百科文章

More details of how bitwise operations work can be found here: Wikipedia article about Bitwise operations

这篇关于这个&算子是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆