Time Class Member Functions

In Fig. 9.2, the Time constructor (lines 11–14) initializes the data members to 0—the universal-time equivalent of 12 AM. Invalid values cannot be stored in the data members of a Time object, because the constructor is called when the Time object is created, and all subsequent attempts by a client to modify the data members are scrutinized by function setTime (discussed shortly). Finally, it’s important to note that you can define overloaded constructors for a class—we studied overloaded functions in Section 6.17.


 1   // Fig. 9.2: Time.cpp
 2   // Time class member-function definitions.
 3   #include <iostream>
 4   #include <iomanip>
 5   #include <stdexcept> // for invalid_argument exception class     
 6   #include "Time.h" // include definition of class Time from Time.h
 7
 8   using namespace std;
 9
10   // Time constructor initializes each data member to zero.
11   Time::Time()
12      : hour( 0 ), minute( 0 ), second( 0 )
13   {
14   } // end Time constructor
15
16   // set new Time value using universal time
17   void Time::setTime( int h, int m, int s )
18   {
19      // validate hour, minute and second
20      if ( ( h >= 0 && h < 24 ) && ( m >= 0 && m < 60 ) &&
21         ( s >= 0 && s < 60 ) )
22      {
23         hour = h;
24         minute = m;
25         second = s;
26      } // end if
27      else
28         throw invalid_argument(                            
29            "hour, minute and/or second was out of range" );
30   } // end function setTime
31
32   // print Time in universal-time format (HH:MM:SS)
33   void Time::printUniversal() const
34   {
35      cout << setfill( '0' ) << setw( 2 ) << hour << ":"
36         << setw( 2 ) << minute << ":" << setw( 2 ) << second;
37   } // end function printUniversal
38
39   // print Time in standard-time format (HH:MM:SS AM or PM)
40   void Time::printStandard() const
41   {
42      cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":"
43         << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 )
44         << second << ( hour < 12 ? " AM" : " PM" );
45   } // end function printStandard


Fig. 9.2. Time class member-function definitions.

Image

Before C++11, only static const int data members (which you saw in Chapter 7) could be initialized where they were declared in the class body. For this reason, data members typically should be initialized by the class’s constructor as there is no default initialization for fundamental-type data members. As of C++11, you can now use an in-class initializer to initialize any data member where it’s declared in the class definition.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.20.193