Chapter 12. Advanced Types
Total grandeur of a total edifice, Chosen by an inquisitor of structures.
C++ provides a rich set of data types. Through the use of structures, unions, enumerations, and class types, the programmer can extend the language with new types.
Structures
Suppose you are writing an inventory program for a warehouse. The warehouse is filled with bins, each containing a bunch of parts. All the parts in a bin are identical, so you don’t have to worry about mixed bins or partials.
For each bin you need to know:
The name of the part it holds (30-character string).
The quantity on hand (integer).
The price (integer cents).
In previous chapters you have used arrays for storing a group of similar data types, but in this example you have a mixed bag: two integers and a string.
Instead of an array, you will use a new data type called a structure. In an array, all the elements are of the same type and are numbered. In a structure, each element, or member, is named and has its own data type.
The general form of a structure definition is:
structstructure-name{member-typemember-name;//Commentmember-typemember-name; //Comment. . . . }variable-name;
For example, say you want to define a bin to hold printer cables. The structure definition is:
struct bin {
char name[30]; // Name of the part
int quantity; // How many are in the bin
int cost; // The cost of a single part (in cents)
} printer_cable_box; // Where we put the print cablesThis definition actually tells ...