我正在尝试了解ios流的格式化标志。谁能解释这个cout.setf(ios::hex | ios::showbase)
的工作原理吗?我的意思是or(|
)运算符如何在两个ios格式的标志之间工作?
请原谅我英语不好。
最佳答案
std::ios_base::hex
和std::ios_base::showbase
都是BitmaskType std::ios_base::fmtflags
的枚举器。 BitmaskType通常是一种枚举类型,其枚举数是2的不同幂,有点像这样:(1 << n
表示2n)
// 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
// ...
};
|
运算符是bit-or运算符,它对相应的位执行or运算,因此hex 0000 0000 0000 0100
showbase 0000 0010 0000 0000
-------------------
hex | showbase 0000 0010 0000 0100
该技术可用于将标志组合在一起,因此位掩码中的每个位都代表一个单独的标志(置位或未置位)。然后,每个标志可以是
mask & flag
; mask | flag
; mask & (~flag)
。 关于c++ - ios::fmtflags如何在C++中工作?setf()如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60236071/