我知道可以在初始化fstream的实例时添加选项,例如:
fstream file("filename.txt", ios::in | ios::out | ios::binary);
在这种情况下,有 3 个选项。 我有几个问题:
- 我应该如何在我自己的职能中实现它?
- 我应该定义任何常量值或宏吗?
- 如何解析选项并正确处理它们?
最佳答案
How should I implement that in my own function?
让它成为bitmask type :
The bitmask type supports a finite number of bitmask elements, which are distinct non-zero values of the bitmask type, such that, for any pair
Ci
andCj
,Ci & Ci != 0
andCi & Cj == 0
. In addition, the value0
is used to represent an empty bitmask, with no values set.
Should I define any const values or macros?
这些值通常是表示 2 的连续幂的常量,即 1、2、4、8、16 等。
How to parse the options and deal with the them properly?
你永远不需要“解析”这些选项——你需要做的就是检查给定的选项是否存在。您可以使用 &
运算符:
openmode x = ios::in | ios::out;
if (x & ios::in) {
... // TRUE
}
if (x && ios::binary) {
... // False
}
关于c++ - 在 C++ 中用逻辑 OR ("|") 分隔选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45760275/