简体   繁体   English

什么是| 运算符在函数调用中的意思? [C ++]

[英]What does the | operator mean in a function call? [C++]

I usually see this when looking at Win32 gui code. 我在查看Win32 gui代码时经常会看到这个。 My assumption is that it is a standard bitwise or, but I also occasionaly see it in C#, and it seems like there would be a better (well higher level) way to do the same thing there. 我的假设是它是一个标准的按位或者,但我也偶尔在C#中看到它,似乎会有一个更好的(更高级别)方式来做同样的事情。 Anyway, here's an example: 无论如何,这是一个例子:

MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);

Thanks, 谢谢,

Seamus 西莫

The | | is a bitwise OR. 是一个按位OR。 MB_OK and MB_ICONEXCLAMATION are defined constants which are a power of 2 (such as 32 or 128), so that the bitwise OR can combine them (128 | 32 would be 160, which has two bits set). MB_OK和MB_ICONEXCLAMATION是定义的常量,它是2的幂(例如32或128),因此按位OR可以组合它们(128 | 32将是160,其中设置了两个位)。 This is normal when the bits are used as flags. 当这些位用作标志时,这是正常的。

Its for bitmasking. 它用于bitmasking。 Lets use this incredibly trivally example. 让我们使用这个令人难以置信的简单例子。 You have a binary value for colors, with the following values. 您有颜色的二进制值,具有以下值。

100 = BLUE 100 =蓝色

010 = RED 010 =红色

001 = GREEN 001 =绿色

When you say SomeFunction ( BLUE | RED | GREEN ); 当你说SomeFunction(BLUE | RED | GREEN); you are infact passing the value 111, which can then be decoded to mean BLUE and RED and GREEN. 你实际上传递了值111,然后可以将其解码为蓝色和红色和绿色。

Google Bitwise operators for more details. Google Bitwise运营商了解更多详情。

It's the bitwise or operator like other places. 它是像其他地方一样的按位或运算符。 Basically, this technique is used when you want to set some attributes that are not mutually exclusive. 基本上,当您想要设置一些非互斥的属性时,会使用此技术。

The function can easily check them with some code like this: 该函数可以使用以下代码轻松检查它们:

if (arg & MB_ICONEXCLAMATION) { // Show an exclamation icon...

}

// ...

if (arg & MB_OK) { // Show an OK button

}

Think of MB_ICONEXCLAMATION and MB_OK as "options" that aren't anything fancier than ints. 将MB_ICONEXCLAMATION和MB_OK视为“选项”,它们不比整数更漂亮。 What you care about is the bit representation of those ints. 你关心的是那些整数的位代表。

Say: 说:

//MessageBox.cs or whatever
public static int MB_ICONEXCLAMATION = 0x1 // 0001 in binary
public static int MB_OK = 0x2 // 0010 in binary

When you OR them together, you get 0011 in binary. 当你将它们组合在一起时,你会得到二进制的0011。 So you are requesting both options for the MessageBox using just one argument instead of having to have more arguments, one for each option you want to specify. 因此,您只使用一个参数为MessageBox请求两个选项,而不是必须有更多参数,每个参数对应您要指定的每个选项。

这是一个按位OR。

It does a bitwise or. 它有点或。

int x = 5 | int x = 5 | 3; 3; // x == 7 now // x == 7现在

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

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