前置++ 和 后置++ 重载的区别

#ifndef _TIME_H_
#define _TIME_H_
#include <iostream>
using namespace std;
class CTime
{
public:
	CTime();
	~CTime();
	friend istream& operator>>(istream& is, CTime &time);//输入 必须定义成友元函数(不需要通过对象名访问私有成员),必须返回引用,因为这样才能连续的输出和输出
	friend ostream& operator<<(ostream& os, CTime &time1);//输入
	CTime& operator++();//前置++重载 返回的必须是引用,因为&可以作为赋值运算的左值
	CTime operator++(int);//后置++重载
	void Print();

private:
	int m_s;
	int m_m;
	int m_h;
};
#endif


#include "Time.h"
#include <iostream>
using namespace std;

CTime::CTime()
{
}


CTime::~CTime()
{
}
istream& operator>>(istream& is, CTime &time)
{
	int h, m, s;
	do
	{
		cout << "请输入时钟,分钟,秒钟" << endl;
		is >> h >> m >> s;
	} while (h > 24 || m > 60 || s > 60);
	time.m_h = h;
	time.m_m = m;
	time.m_s = s;
	return is;
}
ostream& operator<<(ostream& os, CTime &time1)
{
	os << time1.m_h << ":" << time1.m_m << ":" << time1.m_s << endl;
	return os;
}
CTime &CTime::operator++()
{
	(this->m_s)++;
	Print();
	return *this;
}

CTime CTime::operator++(int)
{
	CTime t;//定义一个临时变量
	t.m_s = this->m_s;
	t.m_m = this->m_m;
	t.m_h = this->m_h;

	(this->m_s)++;
	Print();
	return t;//其实自身已经++,但返回的是临时变量
}
void  CTime::Print()
{
	if (this->m_s = 59)
	{
		this->m_s = 0;
        this->m_m += 1;
	}
	if (this->m_m = 59)
	{
		
		this->m_m = 0;
        this->m_h += 1;
	}
	if (this->m_h >= 24)
	{
		this->m_h = 24;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_41946900/article/details/82193889