Sams Teach Yourself C++ in 21 Days

(singke) #1
often four bytes on a machine with a 32-bit processor. By using bit fields, you can store
eight binary values in a charand 32 such values in a four-byte integer.
Here’s how bit fields work: Bit fields are named and accessed the same as any class
member. Their type is always declared to be unsigned int. After the bit field name,
write a colon followed by a number.
The number is an instruction to the compiler as to how many bits to assign to this vari-
able. If you write 1, the bit represents either the value 0 or 1. If you write 2, two bits are
used to represent numbers; thus, the field would be able to represent 0 , 1 , 2 , or 3 , a total
of four values. A three-bit field can represent eight values, and so forth. Appendix A
reviews binary numbers. Listing 21.7 illustrates the use of bit fields.

LISTING21.7 Using Bit Fields
0: #include <iostream>
1: using namespace std;
2: #include <string.h>
3:
4: enum STATUS { FullTime, PartTime } ;
5: enum GRADLEVEL { UnderGrad, Grad } ;
6: enum HOUSING { Dorm, OffCampus };
7: enum FOODPLAN { OneMeal, AllMeals, WeekEnds, NoMeals };
8:
9: class student
10: {
11: public:
12: student():
13: myStatus(FullTime),
14: myGradLevel(UnderGrad),
15: myHousing(Dorm),
16: myFoodPlan(NoMeals)
17: {}
18: ~student(){}
19: STATUS GetStatus();
20: void SetStatus(STATUS);
21: unsigned GetPlan() { return myFoodPlan; }
22:
23: private:
24: unsigned myStatus : 1;
25: unsigned myGradLevel: 1;
26: unsigned myHousing : 1;
27: unsigned myFoodPlan : 2;
28: };
29:
30: STATUS student::GetStatus()
31: {
32: if (myStatus)

776 Day 21

Free download pdf