栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++电子钟(重载)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++电子钟(重载)

设计一款电子钟类,用于显示时、分、秒

实验要求:

  1. 含有形参有默认值的默认构造函数;
  2. 重载 前缀++ 和 后缀++用于调整时间,每次调整均对秒进行调整,若秒满60,则分加1,若分满60则时加1,时满24,则清零重新开始;
  3. 重载插入运算符 >> 用于输入(设定)时间;
  4. 重载插入运算符 << 用于输出时间。

 

#include
using namespace std;
class Time
{
	friend ostream& operator<<(ostream& cout, Time& t);
	friend istream& operator>>(istream& cin, Time& t);
public:
	Time(int h = 0, int m = 0, int s = 0)
	{
		m_H = h;
		m_M = m;
		m_S = s;
	}
//前缀++运算符重载
	Time& operator++();
//后缀++运算符的重载
	Time operator++(int);
private:
	int m_H;
	int m_M;
	int m_S;
};
Time& Time::operator++()
	{
		if (++m_S >= 60)
		{
			m_S -= 60;
			++m_M;
		}
		if (m_M >= 60)
		{
			m_M -= 60;
			++m_H;
		}
		if (m_H >= 24)
		{
			m_H -= 24;
		}
		return *this;
	}
Time Time::operator++(int)
{
		Time temp= *this;
		m_S++;
		if (m_S >= 60)
		{
			m_S -= 60;
			++m_M;
		}
		if (m_M >= 60)
		{
			m_M -= 60;
			++m_H;
		}
		if (m_H >= 24)
		{
			m_H -= 24;
		}
		return temp;
	}
ostream& operator<<(ostream& cout, Time& t)
{
	cout << t.m_H << ":" << t.m_M << ":" << t.m_S << endl;
	return cout;
}
istream& operator>>(istream& cin, Time& t)
{
	cin >> t.m_H >> t.m_M >> t.m_S;
	return cin;
}
int main()
{
	Time t1;//实例化t1(利用前缀++)
    Time t2;//实例化t2(利用后缀++)
    cout << "请输入时间t1的时,分,秒" << endl;
	cin >> t1;//输入t1的时,分,秒
    cout << "请输入时间t2的时,分,秒" << endl;
    cin >> t2;//输入t2的时,分,秒
	int i = 0;
    int j = 0;
    cout << "t1的电子钟模型如下" << endl;
	for (i = 0; i < 61; i++)
	{
		++t1;
		cout << t1 << endl;
	}
    cout << "t2的电子钟模型如下" << endl;
    for (j = 0; j < 61; j++)
	{
		t2++;
		cout << t2 << endl;
	}
	return 0;
}

限于编者能力有限,请读者批评指正:)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/832418.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号