Create a class called Time that has separate int member data for hours, minutes and seconds. One constructor should initialize this data to 0. and another should initialize it to fixed values. A member function should display it, in 11:59:59 format. Write a program to add time of two objects by overloading '+' operator
class Program
{
static void Main(string[] args)
{
Time a = new Time(12, 48, 10);
Time b = new Time(12, 12, 10);
Time c = a + b;
Console.WriteLine(c);
Console.ReadKey();
}
}
public class Time
{
private int hours;
private int minutes;
private int seconds;
// Default constructor
public Time()
{
hours = minutes = seconds = 0;
}
// Constructor with parameters
public Time(int hours, int minutes, int seconds)
{
this.hours = hours % 24;
this.minutes = minutes % 59;
this.seconds = seconds % 59;
}
// Overloading + operator
public static Time operator +(Time a, Time b)
{
int seconds = a.seconds + b.seconds;
int minutes = 0;
int hours = 0;
if(seconds > 59)
{
if(seconds == 60)
{
seconds = 0;
}
else
{
seconds = seconds % 60;
}
minutes++;
}
minutes += a.minutes + b.minutes;
if(minutes > 59)
{
if(minutes == 60)
{
minutes = 0;
}
else
{
minutes = minutes % 60;
}
hours++;
}
hours += a.hours + b.hours;
if(hours > 23)
{
if(hours == 24)
{
hours = 0;
}
else
{
hours = hours % 24;
}
}
return new Time(hours, minutes, seconds);
}
// Overridden method toString() for displaying data
public override string ToString()
{
return $"{hours}:{minutes}:{seconds}";
}
}
Comments
Leave a comment