位字段(Bit-field)就是数据成员,然而被指定了可存放的位数量,也就是用来存放位数据的值域,必须是整数或枚举,通常使用unsigned
,例如unsigned int
:
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
using Bit = unsigned int;
class File {
Bit modified : 1; // 使用 1 位
Bit mode : 2; // 使用 2 位
const string &filename;
public:
enum modes {READ = 0b01, WRITE = 0b10, READ_WRITE = 0b11};
File(const string &filename, modes mode) : filename(filename), mode(mode) {}
bool isRead() {
return this->mode & READ;
}
bool isWrite() {
return this->mode & WRITE;
}
void write(const string &text) {
if(!this->isWrite()) {
throw runtime_error(this->filename + ":read-only");
}
this->modified = 0b01;
// ...
}
//...
};
int main() {
File foo1("foo1", File::READ);
File foo2("foo2", File::READ_WRITE);
foo2.write("XD");
return 0;
}
每一个位字段在紧跟着的冒号后指定使用的位数量,在允许的状况下,连续定义的位字段成员会紧邻着被配置空间。
位字段成员不可被&
取址,也不可为静态成员。