编写一个程序,实行两个时间相加

本文展示了一个C++程序,用于实现两个时间对象的相加操作。通过定义一个`Time`类,包括构造函数、时间相加的运算符重载友元函数以及显示时间的成员函数,实现了对小时、分钟和秒的累加,并处理了进位问题。在主函数中,创建了三个`Time`对象并展示了相加结果。
摘要由CSDN通过智能技术生成
#include<iostream>
#include<string>
using namespace std;
class Time{
public:
	Time(int h=0,int m=0,int s=0);                   //定义构造函数
	Time operator +(Time&);                          //运算符“+”重载为友元函数
	void disptime(string);                           //定义普通输出成员函数
private:
	int hour;
	int minutes;
	int seconds;
};

Time::Time(int h,int m,int s)                       //构造函数
{
	hour=h;
	minutes=m;
	seconds=s;
}

Time Time::operator +(Time& t)                      //运算符“+”重载为友元函数
{
	Time temp;
	temp.seconds=seconds+t.seconds;
    temp.minutes=minutes+t.minutes;
	temp.hour=hour+t.hour;
	if(temp.seconds >=60)
	{
		temp.minutes=temp.minutes+1;
		temp.seconds=temp.seconds-60;
	}
	if(temp.minutes >=60)
	{	
		temp.hour=temp.hour+1;
	    temp.minutes=temp.minutes-60;
	}
	return temp;
}

void Time::disptime(string str)                           
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值