Sams Teach Yourself C++ in 21 Days

(singke) #1
Managing Arrays and Strings 417

13


19: int main()
20: {
21: Cat Litter[5];
22: int i;
23: for (i = 0; i < 5; i++)
24: Litter[i].SetAge(2*i +1);
25:
26: for (i = 0; i < 5; i++)
27: {
28: cout << “Cat #” << i+1<< “: “;
29: cout << Litter[i].GetAge() << endl;
30: }
31: return 0;
32: }

cat #1: 1
cat #2: 3
cat #3: 5
cat #4: 7
cat #5: 9
Lines 5–17 declare the Catclass. The Catclass must have a default constructor
so that Catobjects can be created in an array. In this case, the default constructor
is declared and defined on line 8. For each Cat, a default age of 1 is set as well as a
default weight of 5. Remember that if you create any other constructor, the compiler-
supplied default constructor is not created; you must create your own.
The first forloop (lines 23 and 24) sets values for the age of each of the five Catobjects
in the array. The second forloop (lines 26–30) accesses each member of the array and
calls GetAge()to display the age of each Catobject.
Each individual Cat’s GetAge()method is called by accessing the member in the array,
Litter, followed by the dot operator (.), and the member function. You can access other
members and methods in the exact same way.

Declaring Multidimensional Arrays ..............................................................


It is possible to have arrays of more than one dimension. Each dimension is represented
as a subscript in the array. Therefore, a two-dimensional array has two subscripts; a
three-dimensional array has three subscripts; and so on. Arrays can have any number of
dimensions, although it is likely that most of the arrays you create will be of one or two
dimensions.

OUTPUT


LISTING13.4 continued


ANALYSIS
Free download pdf