#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << setiosflags(ios::left | ios::showpos) << 45 << endl;
return 0;
}
据我所知,按位运算符与 int 数字一起使用来操作位。但在这里它似乎像做这两项工作一样工作,我的意思是 ios::left 然后做 ios::showpos 部分。但我不理解 | 的使用接线员在这里。谁能解释一下为什么?在这里被用来做这样的工作
最佳答案
按位 or
运算符可用于“按位组合”值,例如结果:0010 | 0001
将是:0011
看到设置为 true 的 2 位在结果中都设置为 true。
如果设置了特定位,则按位和
可用于检查值。
检查这个更简单的例子:
enum FlagValues
{
//note: the values here need to be powers of 2
FirstOption = 1,
SecondOption = 2,
ThirdOption = 4,
ForthOption = 8
};
void foo(int bitFlag)
{
//check the bitFlag option with binary and operator
if(bitFlag & FirstOption)
std::cout << "First option selected\n";
if(bitFlag & SecondOption)
std::cout << "Second option selected\n";
if(bitFlag & ThirdOption)
std::cout << "Third option selected\n";
//...
}
int main()
{
//note: set the bits into a bit flag with
int bitFlag = 0;
bitFlag |= FirstOption; // add FirstOption into bitFlag
bitFlag |= ThirdOption; // add ThirdOption into bitFlag
std::cout << "bitFlagValue is: " << bitFlag << '\n';
//call foo with FirstOption and the ThirdOption
foo(bitFlag);
return 0;
}
关于c++ - | 有什么用(按位或运算符)在 setiosflags 的上下文中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57542751/