我正在尝试了解 ios 流的格式化标志。谁能解释一下这个cout.setf(ios::hex | ios::showbase)
东西是如何工作的?我的意思是 or ( ) 运算符如何|
在两个 ios 格式的标志之间工作?请原谅我的英语不好。
问问题
162 次
1 回答
1
std::ios_base::hex
并且std::ios_base::showbase
都是BitmaskType std::ios_base::fmtflags
的枚举数。BitmaskType通常是一种枚举类型,其枚举数是 2 的不同幂,有点像这样:(1 << n
表示 2 n)
// simplified; can also be implemented with integral types, std::bitset, etc.
enum fmtflags : unsigned {
dec = 1 << 0, // 1
oct = 1 << 1, // 2
hex = 1 << 2, // 4
// ...
showbase = 1 << 9, // 512
// ...
};
该|
运算符是位或运算符,它对相应的位执行或操作,所以
hex 0000 0000 0000 0100
showbase 0000 0010 0000 0000
-------------------
hex | showbase 0000 0010 0000 0100
此技术可用于将标志组合在一起,因此位掩码中的每个位都代表一个单独的标志(设置或取消设置)。然后,每个标志可以是
查询:
mask & flag
;设置:
mask | flag
;未设置:
mask & (~flag)
。
于 2020-02-15T09:14:25.250 回答