C++ program to perform following task

Write a C++ program that performs the following tasks:

Create a class called Time with following data members:
         A variable to store hours
         A variable to store minutes

Design constructors for object creation in following manner:
         Time t1 ;
// Creates an object with time as 00 : 00
         Time t2 ( 5 ) ;
// Creates an object with time as 05 : 00
         Time t3 ( 5, 30 ) ;
// Creates an object with time as 05 : 30
         Time t4 ( t3 ) ;
// Creates an object with time as stored in t3 object

Overload appropriate operators to perform following tasks:
         cin >> objT2 ;
// Inputs hours and minutes from input device
         cout << objT2 ;
// Outputs time in HH:MM format
         t3 = t1 + t2 ;
// Adds time of t1 and t2 objects
// and stores in t3 object
         t1 += 90 ;
// Adds the value 50 to the object.
// i.e it actually adds 1 hour and 30 minutes
        cout << objT1 [ 0 ] ;
// Displays the hour part of the time
        cout << objT1 [ 1 ] ;
// Displays the minute part of the time


Program:

#include"iostream"
#include"cstring"
#include"fstream"

using namespace std;

class Time
{

    int hr, min;
public:
    Time()
    {
        hr = min = 00;
      
    }
   
    Time(int h)
    {
        hr = h;
        min = 00;
        cout<<"Time is: "<<hr<<":"<<min<<endl;
    }

    Time(int h, int m)
    {
        hr = h;
        min = m;
        cout<<"Time is: "<<hr<<":"<<min<<endl;
    }

    Time(Time & t)
    {
        hr = t.hr;
        min = t.min;
        cout<<"Time is: "<<hr<<":"<<min<<endl;
    }

    Time operator + (Time & t)
    {
        Time tm;
        tm.hr = hr + t.hr;
        tm.min = min + t.min;
        return tm;
    }

    Time operator += (int tt)
    {
      
        int n;
        n = tt / 60;
        hr = hr + n;
        min = tt % 60;
      
    }
   
    int & operator [] (int index)
    {
        if(index == 0)
            return hr;
        else if (index == 1)
            return min;
    }
    friend istream & operator >> (istream &, Time &);
    friend ostream & operator <<(ostream &, Time &);
};

istream & operator >> (istream & fin, Time & t)
{
    cout<<"Enter hour: ";
    fin>>t.hr;
    cout<<"Enter minute: ";
    fin>>t.min;
   
}

ostream & operator << (ostream & fout, Time & t)
{
    fout<<"Time is: "<<t.hr<<":"<<t.min<<endl;
}
int main()
{

    Time t1;
    Time t2(5);
    Time t3(5, 30);
    cout<<"\n--------- Copy Constructor ---------\n";
    Time t4(t3);
    cout<<"\n--------- Overloading << and >> Operator ---------\n";
    Time objT2;
    cin>>objT2;
    cout<<objT2;
    cout<<"\n--------- Overloading + Operator ---------\n";
    t3 = t3 + t2;
    cout<<t3;
   
    cout<<"\n--------- Overloading += Operator ---------\n";
    t1 += 90;
    cout<<t1;

    cout<<"\n--------- Overloading subscript [] Operator ---------\n";
    cout<<objT2[0]<<":"<<objT2[1]<<endl;
   
}


Output:

 

Comments

Popular Posts