CHAPTER 11 实验题 3 4

第三题:(和第十章的相似)

第四题:

Time.h

class Time
{
public:
	void Set(int hours,int minutes,int seconds);
	void Increament();
	void Write() const;

	bool Equal(/* in */ Time otherTime) const;
	bool LessThan(/* in*/ Time otherTime) const;

	Time();//无参构造
	Time(int initHrs, int initMins, int initSecs);

private:
	int hrs;
	int mins;
	int secs;
};   // !!!!!!!!!!!!!!!!!!注意标点符号!!!!!!!!!!

Q4.cpp (main.cpp)

#include<iostream>
#include"Time.h"

using namespace std;


int main()
{
	Time time1(5,10,30);
	Time time2;

	int LoopCount=0;
	cout<<"time1 ";
	time1.Write();

	cout<<"time2 ";
	time2.Write();

	cout<<endl;

	if(time1.Equal(time2))
		cout<<"Equal "<<endl;
	else 
		cout<<"Not Equal "<<endl;
 
	time2=time1;

	cout<<"time1 ";
	time1.Write();

	cout<<"time2 ";
	time2.Write();

	cout<<endl;

	if(time1.Equal(time2))
		cout<<"Equal "<<endl;
	else 
		cout<<"Not Equal "<<endl;

	time2.Increament();
	cout<<"New time2 ";
	time2.Write();

	cout<<endl;

	if(time1.LessThan(time2))
	cout<<"less than time2 ";
	else
		cout<<"not less than time2 "<<endl;

	if(time2.LessThan(time1))
	cout<<"less than time1 ";
	else
		cout<<"not less than time1 "<<endl;
	
	time1.Set(23,59,55);
	cout<<"Increamenting Time1 from 23:59:55: "<<endl;

	for(LoopCount=1;LoopCount<=10;LoopCount++)
	{
		time1.Write();
		cout<<"  ";
		time1.Increament();
	}

	cout<<endl;
	cin.get();
	return 0;
}

Time.cpp

#include<iostream>
#include"Time.h"

using namespace std;

void Time::Set(int hours,int minutes,int seconds)
{
	hrs=hours;
	mins=minutes;
	secs=seconds;
}

void Time::Increament()
{
	secs++; //函数名前边加作用域的好处,可以不至于变量名报错:未命名标识符
	if(secs>59)
	{
		secs=0;
		mins++;
		if(mins>59)
		{
			mins=0;
			hrs++;
			if(hrs>23)
			{
				hrs=0;
			}
		}
	}
}


void Time::Write() const
{
	if(hrs<10)
			cout<<'0';
			cout<<hrs<<": ";
	if(mins<10)
			cout<<'0';
			cout<<mins<<": ";
	if(secs<10)
			cout<<'0';
			cout<<secs<<endl;
}

bool Time::Equal(/* in */ Time otherTime) const
{
	return (hrs==otherTime.hrs && mins==otherTime.mins && secs==otherTime.secs);
}
	

bool Time::LessThan(/* in*/ Time otherTime) const{
	return (hrs<otherTime.hrs || hrs==otherTime.hrs 
		&& mins<otherTime.mins || mins==otherTime.mins 
		&& secs<otherTime.secs || secs==otherTime.secs);
}
 
Time::Time()
{   hrs=0;
	mins=0;
	secs=0;
}


Time::Time(int hours,int minutes,int seconds){
	hrs=hours;
	mins=minutes;
	secs=seconds;
}

运行结果:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

懒回顾,半缘君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值