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

What is use of | (bitwise or operator ) in the context of setiosflags?

本文关键字:setiosflags 上下文 运算符 位或 什么      更新时间:2023-10-16
#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。

按位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 selectedn";
if(bitFlag & SecondOption)
std::cout << "Second option selectedn";
if(bitFlag & ThirdOption)
std::cout << "Third option selectedn";
//...
}
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;
}

所有 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 将它们"添加"在一起变得容易。