Sams Teach Yourself C in 21 Days

(singke) #1
prototypes are provided in lines 13–15, and the actual functions are in lines 59–82. In
lines 29, 30, and 31, the main()function passes the address of the end_timestructure to
each of the add...functions. The add...functions then add the appropriate value to the
structure’s member variables.
A little bit of additional functionality has been added to this listing. Each of the add...
functions includes a few lines of code that check if the value is large enough to incre-
ment the larger time unit. For example, 60 seconds equals one minute. When the seconds
hit 60, the add_minute()function is called, and the minutes are reset. Similar logic is
applied to the hours and minutes functions as well.

670 Bonus Day 3

You also see that the values for the structures are initialized differently in
this listing. Rather than initializing each data member individually, the initial
values are placed in the structures as they are declared (see lines 19 and 20).
This can be done in both C and C++.

Note


If you are uncomfortable with the way Listing B3.2 is using pointers, you
Tip should review Days 9 and 11 that cover the use of pointers.

Using Member Functions
In Bonus Day 1, you learned about the features of an object-oriented language. One of
these features is encapsulation. In Bonus Day 1, you learned that encapsulation describes
the capability to create objects that are self-contained. In C++, you can actually make the
time structure more self-contained by associating the functions that have been created in
Listing B3.2 with the timestructure itself. Just as you have the member data variables
(hours, minutes, and seconds), you can also have member functions. These member func-
tions can be part of your structure in the same way as the data members. Listing B3.3
presents a similar Listing to B3.2; however, in this listing add_hour(),add_minute(),
add_second(), anddisplay_time()are all member functions of the timestructure.

LISTINGB3.3 time3.cpp. Using member functions in the timestructure
1: // Program using a time structure with member functions
2: //
3: #include <iostream.h>
4:

38 448201x-Bonus3 8/13/02 11:19 AM Page 670

Free download pdf