Answer to Question #248854 in C++ for Himanshu

Question #248854

Write a program to subtract two time object using operator member function.


1
Expert's answer
2021-10-09T04:45:11-0400
#include <iostream>
class Time
{
public:
	void viewTime()
	{
		std::cerr << m_sign << m_hour << ":" << m_min << ":" << m_sec << "\n";
	}
	Time(int h,int  m, int s) 
	{
		int sum_s;
		sum_s = 3600 * h + 60 * m + s;
		if (sum_s < s) 
		{
			m_sign = '-' ;
			sum_s *= -1;
		}
		m_hour =sum_s/3600;
		sum_s -= m_hour * 3600;
		m_min = sum_s / 60;
		sum_s -= m_min * 60;
		m_sec =sum_s;
	}
     Time operator - (const Time &t1) 
	{
		return Time(this->m_hour-t1.m_hour,
			               this->m_min - t1.m_min, 
			               this->m_sec - t1.m_sec);
	}
	int m_hour{ 0 };
	int m_min{ 0 };
	int m_sec{ 0 };
	char m_sign{};
private:
};

int main()
{
	// as example
	Time t1(10, 12, 45);
	Time t2(9, 56, 50);
	Time t3 =t1-t2;
	t3.viewTime();
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS