Thursday, November 15, 2012

C++ classes: Time

____________________________________

First: Header file.h (functions prototype).

____________________________________ 
//File: Time.h  Time Class Header File
#ifndef TIME_H    // used to avoid multiple definitions
#define TIME_H    // not part of the class
class Time
{
    public:
        Time();          // constructor
        ~Time();     // destructor
        // Function prototypes
        void setTime(int, int, int );
        void displayTime() const;
    private:
        int hour, minute, second;        
}; // a semicolon must appear here
#endif  // TIME_H



________________________________________________ 

second: Implementation file.cpp 

_____________________________________
  
//File: Time.cpp  Time Class Implementation File
#include "Time.h"
#include <iostream>
using namespace std;

Time::Time()
{    hour = minute = second = 0; }

Time::~Time()
{ }

void Time::setTime(int h, int m, int s)
  {
     hour   = (h >= 0 && h < 24) ? h : 0;
     minute = (m >= 0 && m < 60) ? m : 0;
     second = (s >= 0 && s < 60) ? s : 0;
  }

void Time::displayTime() const
{ cout << hour << ":" << minute << ":" << second << endl; }
________________________________________________ 

finally class test

_____________________________________
//File: TimeAppl.cpp  Time Class Application File
#include "Time.h"
#include "Time.cpp"
#include <iostream>
using namespace std;
int main()
{
    Time t1 , t2;
    cout << "Start Time is: ";     t1.displayTime();
    t2.setTime(5, 10, 30);
    cout << "End Time is: ";    t2.displayTime();
    return 0;
}
 




No comments:

Post a Comment