Program 1
#include
#include
#ifndef time_h
#define time_h
class time
{
private:
int hour;
int minute;
int second;
public:
time(int h = 0, int m = 0, int s = 0);
int gethour() const;
void sethour(int h);
int getminute() const;
void setminute(int m);
int getsecond() const;
void setsecond(int s);
void settime(int h, int m, int s);
void print() const;
};
Program 2
#include
#include
#include
#include
#include
using namespace std;
time::time(int h, int m, int s)
{
sethour(h);
setminute(m);
setsecond(s);
}
int time::gethour() const
{
return hour;
}
void time::sethour(int h)
{
if (h >= 0 && h <= 23)
{
hour = h;
}
else
{
throw invalid_argument("Invalid hour! Hour shall be 0-23.");
}
}
int time::getminute() const
{
return minute;
}
void time::setminute(int m)
{
if (m >= 0 && m <= 59)
{
minute = m;
}
else
{
throw invalid_argument("Invalid minute! Minute shall be 0-59.");
}
}
int time::getsecond() const
{
return second;
}
void time::setsecond(int s)
{
if (s >= 0 && s <= 59)
{
second = s;
}
else
{
throw invalid_argument("Invalid second! Second shall be 0-59.");
}
}
void time::settime(int h, int m, int s)
{
sethour(h);
setminute(m);
setsecond(s);
}
void time::print() const
{
cout << setfill('0');
cout << setw(2) << hour << ":" << setw(2) << minute << ":"
<< setw(2) << second << endl;
}
Program 3
#include
#include
#include
#include
using namespace std;
int main()
{
time t2(25, 0, 0);
t2.print();
try
{
time t1(25, 0, 0);
t1.print();
}
catch (invalid_argument& ex)
{
cout << "Exception: " << ex.what() << endl;
}
cout << "Next statement after try-catch" << endl;
}
No comments:
Post a Comment