|
|
|
|
|
|
|
*intPtr = 28;
cout < intPtr < endl;
cout < *intPtr < endl; |
|
|
|
|
|
|
|
|
The first output statement prints the contents of intPtr (5008); the second prints the contents of the variable pointed to by intPtr (28). |
|
|
|
|
|
|
|
|
Let's look at a more involved example of declaring pointers, taking addresses, and dereferencing pointers. The following program fragment declares several types and variables. In this code, the TimeType class is the C++ class we developed in Chapter 15 with member functions Set, Increment, Write, Equal, and LessThan. |
|
|
|
|
|
|
|
|
#include timetype.h // For TimeType class
.
.
.
enum ColorType {RED, GREEN, BLUE};
struct PatientRec
{
int idNum;
int height;
int weight;
};
int alpha;
ColorType color;
PatientRec patient;
TimeType startTime(8, 30, 0);
int* intPtr = α
ColorType* colorPtr = &color;
PatientRec* patientPtr = &patient;
TimeType* timePtr = &startTime; |
|
|
|
|
|
|
|
|
The variables intPrt, colorPtr, patientPtr, and timePtr are all pointer variables. intPtr points to (contains the address of) a variable of type int; colorPtr points to a variable of type Color;patientPtr points to a struct variable of type PatientRec; and timePtr points to a class object of type TimeType. |
|
|
|
|
|
|
|
|
The expression *intPtr denotes the variable pointed to by intPtr. The pointed-to variable can contain any int value. The expression *colorPtr denotes a variable of type ColorType. It can contain RED, GREEN, or BLUE. The |
|
|
|
|
|