c++ - | 有什么用(按位或运算符)在 setiosflags 的上下文中?

标签 c++ bitwise-operators

#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/

相关文章:

c - 为什么左移操作不起作用

c++ - 我可以生成一个大小为 n 的常量数组吗

C++ 是否有任何关于如何使用句柄的教程?

c++ - 为什么 (rand() % anything) 在 C++ 中总是 0?

c - 除法期间 float 的位会发生什么变化?

c++ - if( !(s & i) ) 和 if( s&i == 0 ) 有什么区别?

c - 在 C 中将两个 8 位寄存器读入 ADXL362 的 12 位值

c++ - 有没有办法在 g++/clang++ 中使用自定义修改?

c++ - 初始化结构 vector 的 vector 的好方法(每个 vector 都有一个初始值)?

c - 我怎样才能使这种按位运算更快?