Sams Teach Yourself C in 21 Days

(singke) #1
Working with C++ Classes and Objects 667

BD3


18: start_time.hours = 8;
19: start_time.minutes = 15;
20: start_time.seconds = 20;
21:
22: end_time.hours = 10;
23: end_time.minutes = 11;
24: end_time.seconds = 12;
25:
26: cout << “\nStart time: “;
27: print_time(start_time);
28: cout << “\n\nEnd time: “;
29: print_time(end_time);
30:
31: return 0;
32: }
33:
34: // Print a time structure in h:m:s format
35: //----------------------------------------
36: void print_time(struct time tm)
37: {
38: cout << tm.hours << “:” << tm.minutes << “:” << tm.seconds;
39: }

Start time: 8:15:20
End time: 10:11:12
Listing B3.1 presents a simple structure in lines 5–9 that holds the time in hours,
minutes, and seconds. In lines 15 and 16 two structures are declared as
start_timeandend_time. The data members of each of these time structures are initial-
ized in lines 18–24. The time values are then printed out in the function
display_time(), which is prototyped in line 11 and defined in lines 36–39.

Using Functions with Structures ..................................................................


Listing B3.1 uses a structure to create a time data element. There are a number of func-
tions you can associate with the time structure. You have already seen a simple function
calleddisplay_time(). The following are additional functions that can be directly asso-
ciated with the time structure:
add_hour()
add_minute()
add_second()

LISTINGB3.1 continued

OUTPUT

ANALYSIS

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

Free download pdf