|= 在 C++ 中是什么意思

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31905898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:03:06  来源:igfitidea点击:

What does |= means in c++

c++

提问by vico

I have code line

我有代码行

int i =0;
result |= EXPECT_EQUAL(list.size(),     3);

What does |=mens?

什么是|=男士?

I was trying to compile something like:

我试图编译类似的东西:

int result |= 5;

but got error:

但有错误:

aaa.cpp:26:16: error: expected initializer before ‘|=' token

回答by Serge Ballesta

a |= b;is just syntactic sugar for a = a | b;. Same syntax is valid for almost every operator in C++.

a |= b;只是a = a | b;. 相同的语法对 C++ 中的几乎所有运算符都有效。

But int i |= 5;is an error, because in the definition line you must have an initialisation, that is an expression that does not use the variable being declared.

但这int i |= 5;是一个错误,因为在定义行中您必须有一个初始化,即一个不使用被声明的变量的表达式。

int i=3;
i |= 5;

is valid and will give value 7 (3 | 5) to i.

是有效的,并且会给 7 (3 | 5) 值i

回答by Christian Hackl

It's the operator for assignment by bitwise OR.

它是按位 OR 赋值的运算符。

http://en.cppreference.com/w/cpp/language/operator_assignment

http://en.cppreference.com/w/cpp/language/operator_assignment

int result |= 5;
int result |= 5;

You cannot initialize an intand assign something to it at the same time. Initialization and assignment are different things. You'd have to write:

您不能同时初始化一个int并为其分配一些东西。初始化和赋值是不同的事情。你必须写:

int result = 0;
result |= 5;

If this is what you intend, of course. Since int result |= 5;is not C++, we can only guess about your intention.

当然,如果这是您的意图。由于int result |= 5;不是C++,我们只能猜测你的意图。