什么是用途 |(按位或运算符)在setiosflags的上下文中?
What is use of | (bitwise or operator ) in the context of setiosflags?
#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 将它们"添加"在一起变得容易。
相关文章:
- #为""定义宏;静态";针对不同的上下文
- 与互斥锁相比,旋转锁可以保证上下文切换
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么我不能使用 EGL 创建无头 OpenGl 上下文?
- C++setiosflags函数操纵器-未确定的缩进
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- 错误"Could not find Boost"(缺少:上下文标头)
- 使用 mod_gsoap 部署服务时,如何在 Gsoap 中更改 soap 上下文的模式?
- 将有状态的 lambda 传递到 C 样式函数中,而无需上下文参数
- 安排带有上下文的协同程序
- 我的文件无法正常工作,无法从C++文件中读取上下文
- DCMTK 了解"DIMSE 没有有效的演示上下文 ID"错误
- 具有std::initializer_list参数的非成员函数(/non构造函数上下文)的重载解析
- antlr 规则上下文是否可以独立于目标
- OpenGL 调试上下文警告 -"将使用视频内存作为缓冲区异议的来源
- 在setiosflags函数中使用十六进制标志
- MSVC 在不知道类型的情况下评估上下文(和错误)
- 为什么 Perf 具有如此高的上下文切换?
- 非推导上下文,如标准库中的"boost::mpl::identity:<T>:type"?