c++ - 有什么用| (按位或运算符)在 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 部分。但我不理解 | 的使用 操作员在这里。谁能解释我为什么?在这里被用来做这种工作
解决方案
位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;
}
推荐阅读
- c++ - AddressSanitizer:DEADLYSIGNAL ==31==ERROR: AddressSanitizer: SEGV 在未知地址
- java - 从 ResultSet 读取 Sybase 列时,我得到“JZ006:Caught IOException:java.io.IOException:JZ0R3:Column is DEAD”。
- python - 分别制作熊猫数据框中每个变量的散点图
- python - Python MVC - 尝试将 sqlite 数据库中的数据分配到 tkinter 标签小部件中
- bash - 根据匹配将多个文件存储为变量
- r - 如何在 RMarkdown 的 PDF 输出中旋转表格?
- amazon-web-services - 将fluent-ffmpeg转换后的视频直接上传到s3
- routes - 没有从 LAN 到 KVM/QEMU 虚拟机的路由
- ios - 在 Mac 上复制路径会复制“sers”而不是“users”
- c++ - 重置最大设置位