首页 > 解决方案 > 有什么用| (按位或运算符)在 setiosflags 的上下文中?

问题描述

#include <iostream>
#include <iomanip>
using namespace std;
int main() {

    cout << setiosflags(ios::left |  ios::showpos) << 45 << endl;
    return 0;
}

据我所知,按位运算符与 int number 一起使用来操作位。但在这里似乎它就像做这两项工作一样工作,我的意思是 ios::left 然后做 ios::showpos 部分。但我不理解 | 的使用 操作员在这里。谁能解释我为什么?在这里被用来做这种工作

标签: c++bitwise-operators

解决方案


or运算符可用于“按位组合”值,例如结果:0010 | 0001将是:0011看到被设置为真的 2 位在结果中都设置为真。

如果设置了特定位,则按位and可用于检查值。

检查这个更简单的例子:

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;
}

推荐阅读