什么是| (按位或运算符)在setiosflags的上下文中?

时间:2019-08-18 08:04:13

标签: c++ bitwise-operators

#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部分。但是我不理解|的用法。有人可以解释我为什么在这里被用来做这种工作

2 个答案:

答案 0 :(得分:1)

按位or运算符可用于“按位组合”值,示例结果如下:0010 | 0001将是:0011看到设置为true的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;
}

答案 1 :(得分:0)

所有ios标志都按照实现定义的顺序简单地编码为单独的位。这样就可以简单地按位或与它们一起添加标志。

如果您查看gcc头文件bits/ios_base.h,则会发现以下定义:

enum _Ios_Fmtflags
{
    _S_boolalpha  = 1L << 0,
    _S_dec        = 1L << 1,
    _S_fixed      = 1L << 2,
    _S_hex        = 1L << 3,
    _S_internal   = 1L << 4,
    _S_left       = 1L << 5,
    _S_oct        = 1L << 6,
    _S_right      = 1L << 7,
    _S_scientific     = 1L << 8,
    _S_showbase   = 1L << 9,
    _S_showpoint  = 1L << 10,
    _S_showpos    = 1L << 11,
    _S_skipws     = 1L << 12,
    _S_unitbuf    = 1L << 13,
    _S_uppercase  = 1L << 14,
    _S_adjustfield    = _S_left | _S_right | _S_internal,
    _S_basefield  = _S_dec | _S_oct | _S_hex,
    _S_floatfield     = _S_scientific | _S_fixed,
    _S_ios_fmtflags_end = 1L << 16,
    _S_ios_fmtflags_max = __INT_MAX__,
    _S_ios_fmtflags_min = ~__INT_MAX__
};

以及稍后的几行:

 ....

/// Generates a decimal-point character unconditionally in generated
/// floating-point output.
static const fmtflags showpoint =   _S_showpoint;

/// Generates a + sign in non-negative generated numeric output.
static const fmtflags showpos =     _S_showpos;

/// Skips leading white space before certain input operations.
static const fmtflags skipws =      _S_skipws;

....

如您所见,每个标志都表示为单个特定位。这样可以很容易地使用or将它们“添加”在一起。