c++知识点----输出宽度填充以及运算符重载

题目:

编写一个程序,其中设计一个时间类,用来保存时、分、秒等私有数据成员,通过重载运算符“+”实现两个时间相加。要求将小时限制>=0,分钟[0,59]区间,秒[0,59]区间,输出时、分、秒各保持两个宽度,并用0填充。


用到的文件:



main.cpp:

#include <iostream> 
using namespace std;
#include <iomanip>//输出字符宽度setw()需要的头文件
#include "class.h"

int main()
{
	Time t1(2, 4, 56);
	Time t2(3, 56, 7);
	Time t3 = t1 + t2;
	cout.fill('0');//如果有输出宽度控制,用'0'来填充不足的长度
	t1.show();//输出时间
	t2.show();
	t3.show();
	system("pause");
	return 0;
}

class.h:

#pragma once
class Time
{
public:
	Time(int h,int m,int s);//初始化私有成员
	Time operator+(Time &);//成员重载运算符 --- time类对象相加
	void show();
private:
	int hours;//小时
	int minutes;//分
	int seconds;//秒
};
Time::Time(int h = 0, int m = 0, int s = 0)
{
	hours = h;
	minutes = m;
	seconds = s;
}
inline Time Time::operator+(Time &s)
{
	Time t;
	t.hours = hours + s.hours;
	t.minutes = minutes + s.minutes;
	t.seconds = seconds + s.seconds;
	if (t.seconds >= 60)//将秒进位
	{
		t.seconds -= 60;
		t.minutes++;
	}
	if (t.minutes >= 60)//将分进位
	{
		t.minutes -= 60;
		t.hours++;
	}
	return t;
}
inline void Time::show()
{
	cout << setw(2) << hours << "时";//setw()为控制输出宽度的函数
	cout << setw(2) << minutes << "分";
	cout<< setw(2) << seconds << "秒" << endl;
}

运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值