Datasheet
Behind the scenes, an enumerated type is just an integer value. The real value of kPieceTypeKing is
zero. However, by defining the possible values for variables of type
PieceT, your compiler can give you
a warning or error if you attempt to perform arithmetic on
PieceT variables or treat them as integers.
The following code, which declares a
PieceT variable then attempts to use it as an integer, results in a
warning on most compilers.
PieceT myPiece;
myPiece = 0;
Structs
Structs let you encapsulate one or more existing types into a new type. The classic example of a struct is
a database record. If you are building a personnel system to keep track of employee information, you
will need to store the first initial, last initial, middle initial, employee number, and salary for each
employee. A struct that contains all of this information is shown in the header file that follows.
// employeestruct.h
typedef struct {
char firstInitial;
char middleInitial;
char lastInitial;
int employeeNumber;
int salary;
} EmployeeT;
A variable declared with type EmployeeT will have all of these fields built-in. The individual fields of a
struct can be accessed by using the “.” character. The example that follows creates and then outputs the
record for an employee.
// structtest.cpp
#include <iostream>
#include “employeestruct.h”
using namespace std;
int main(int argc, char** argv)
{
// Create and populate an employee.
EmployeeT anEmployee;
anEmployee.firstInitial = ‘M’;
anEmployee.middleInitial = ‘R’;
anEmployee.lastInitial = ‘G’;
anEmployee.employeeNumber = 42;
anEmployee.salary = 80000;
// Output the values of an employee.
11
A Crash Course in C++
04_574841 ch01.qxd 12/15/04 3:39 PM Page 11