简体   繁体   English

| =运算符在C ++中是什么意思?

[英]What does the |= operator mean in C++?

| =运算符在C ++中是什么意思?

Assuming you are using built-in operators on integers, or sanely overloaded operators for user-defined classes, these are the same: 假设您对整数使用内置运算符,或者对用户定义的类使用重载的运算符,则它们是相同的:

a = a | b;
a |= b;

The ' |= ' symbol is the bitwise OR assignment operator. ' |= '符号是按位或赋值运算符。 It computes the value of OR'ing the RHS ('b') with the LHS ('a') and assigns the result to 'a', but it only evaluates 'a' once while doing so. 它计算将RHS('b')与LHS('a')进行“或”运算的值,并将结果分配给“ a”,但这样做时仅计算一次“ a”。

The big advantage of the '|=' operator is when 'a' is itself a complex expression: '| ='运算符的最大优势在于,'a'本身是一个复杂的表达式时:

something[i].array[j]->bitfield |= 23;

vs: vs:

something[i].array[i]->bitfield = something[i].array[j]->bitfield | 23;

Was that difference intentional or accidental? 这种差异是故意的还是偶然的?

... ...

Answer: deliberate - to show the advantage of the shorthand expression...the first of the complex expressions is actually equivalent to: 答案:故意-显示速记表达式的优点...第一个复杂表达式实际上等效于:

something[i].array[j]->bitfield = something[i].array[j]->bitfield | 23;

Similar comments apply to all of the compound assignment operators: 类似的注释适用于所有复合赋值运算符:

+= -= *= /= %=
&= |= ^=
<<= >>=

Any compound operator expression: 任何复合运算符表达式:

a XX= b

is equivalent to: 等效于:

a = (a) XX (b);

except that a is evaluated just once. 除了a仅被评估一次。 Note the parentheses here - it shows how the grouping works. 请注意此处的括号-它显示分组的工作方式。

x |= y

same as 和...一样

x = x | y

same as 和...一样

x = x [BITWISE OR] y

It is a bitwise OR compound assignment . 这是按位或复合赋值

In the same way as you can write x += y to mean x = x + y 用与您可以将x += y表示为x = x + y相同的方式

you can write x |= y to mean x = x | y 您可以将x |= y表示为x = x | y x = x | y , which ORs together all the bits of x and y and then places the result in x . x = x | y ,将xy所有位进行或运算,然后将结果放入x

Beware that it can be overloaded , but for basic types you should be ok :-) 注意它可以重载 ,但是对于基本类型,你应该没问题:-)

You can try using SymbolHound: the search engine for programmers to search sites like SO for symbols such as this. 您可以尝试使用SymbolHound:程序员的搜索引擎,可以在SO之类的站点中搜索诸如此类的符号。 Here are the results for |= on SymbolHound. 这是SymbolHound上| =的结果 -Tom (cofounder SH) 汤姆(联合创始人SH)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM