A class can define a (nonstatic
) data member as a bit-field. A bit-field holds a specified number of bits. Bit-fields are normally used when a program needs to pass binary data to another program or to a hardware device.
A bit-field must have integral or enumeration type (§ 19.3, p. 832). Ordinarily, we use an unsigned
type to hold a bit-field, because the behavior of a signed
bit-field is implementation defined. We indicate that a member is a bit-field by following the member name with a colon and a constant expression specifying the number of bits:
typedef unsigned int Bit;
class File {
Bit mode: 2; // mode has 2 bits
Bit modified: 1; // modified has 1 bit
Bit prot_owner: 3; // prot_owner has 3 bits
Bit prot_group: 3; // prot_group has 3 bits
Bit prot_world: 3; // prot_world has 3 bits
// operations and data members of File
public:
// file modes specified as octal literals; see § 2.1.3 (p. 38)
enum modes { READ = 01, WRITE = 02, EXECUTE = 03 };
File &open(modes);
void close();
void write();
bool isRead() const;
void setWrite();
};
The mode
bit-field has two bits, modified
only one, and the other members each have three bits. Bit-fields defined in consecutive order within the class body are, if possible, packed within adjacent bits of the same integer, thereby providing for storage compaction. For example, in the preceding declaration, the five bit-fields will (probably) be stored in a single unsigned int
. Whether and how the bits are packed into the integer is machine dependent.
The address-of operator (&
) cannot be applied to a bit-field, so there can be no pointers referring to class bit-fields.
Ordinarily it is best to make a bit-field an unsigned
type. The behavior of bit-fields stored in a signed
type is implementation defined.
A bit-field is accessed in much the same way as the other data members of a class:
void File::write()
{
modified = 1;
// . . .
}
void File::close()
{
if (modified)
// . . . save contents
}
Bit-fields with more than one bit are usually manipulated using the built-in bitwise operators (§ 4.8, p. 152):
File &File::open(File::modes m)
{
mode |= READ; // set the READ bit by default
// other processing
if (m & WRITE) // if opening READ and WRITE
// processing to open the file in read/write mode
return *this;
}
Classes that define bit-field members also usually define a set of inline member functions to test and set the value of the bit-field:
inline bool File::isRead() const { return mode & READ; }
inline void File::setWrite() { mode |= WRITE; }
3.144.227.9