|
A structured value is a collection of variables, called fields, each with a name and a type. For example, a structured value might contain an integer called item and a const char* pointer called name, as shown in the following diagram.
Structured values (or simply structures) are useful because they allow you to group values and to treat the group as a single value.
Each structured value has a type that must be defined within the program. Define a type of structures using struct. For example,
struct PairOfInts { int a; int b; };creates a new type PairOfInts, where a value of type PairOfInts has two fields, called a and b, each of type int. Type definition
struct Cell { int item; const char* name; };defines type Cell with two fields, corresponding to the diagram above. (Remark: The const designator for field name indicates that the characters in array name cannot be changed. You are free to store a different pointer of type const char* into a structure of type Cell.)
Notice the semicolon at the end of a structure type definition. Be sure to include it.
If module A.cpp exports a structure type, put the type definition in A.h, and only in A.h. If A.cpp does not export the structure type, put the type definition near the beginning of A.cpp.
Write a definition of structure type Employee, where a value of type Employee has three fields: (1) a constant null-terminated string called name, (2) a value of type double called salary and (3) a constant null-terminated string called office.
Answer
|