>>运算符重载,可以像读取字符串一样读取输入流吗?
  • 板块学术版
  • 楼主TLE_Forever
  • 当前回复16
  • 已保存回复16
  • 发布时间2020/5/1 12:01
  • 上次更新2023/11/7 03:29:48
查看原帖
>>运算符重载,可以像读取字符串一样读取输入流吗?
286238
TLE_Forever楼主2020/5/1 12:01

想要重载一下cin>>运算符,让它在输入time类型的时候能够按照如【1:02:49】或【10:56:09】这种形式读取时间。

就是想要把这里面的小时,分钟,秒分别提取出来,赋值到hourminutesecond变量里,忽略分号。

代码:

#include <iostream>
#include <Windows.h>
#include <cstdlib>
#include <string>
#include "Class1.h"
#define STOP (hour && minute && second)
using std::endl;
using std::cout;
using std::cin;
using std::string;
time::time() {
	hour = 0;
	minute = 0;
	second = 0;
}
void time::setTime(int h, int m, int s) {
	hour = h;
	minute = m;
	second = s;
}
time time::operator + (time t) {
	time sum;
	int goon;
	sum.second = t.second + second;
	goon = sum.second / 60;
	sum.second %= 60;
	sum.minute = t.minute + minute + goon;
	goon = sum.minute / 60;
	sum.minute %= 60;
	sum.hour = t.hour + hour + goon;
	return sum;
}
time time::operator - (time t) { // 若被减数小于减数,返回-1, -1, -1
	time end;
	end.setTime(-1, -1, -1);
	if (hour < t.hour) return end;
	else if (hour == t.hour && minute < t.minute) return end;
	else if (hour == t.hour && minute == t.minute && second < t.second) return end;
	else if (hour == t.hour && minute == t.minute && second == t.second) {
		end.setTime(0, 0, 0);
		return end;
	}
	bool geon = false;
	if (second < t.second) {
		geon = true;
		second += 60;
		end.second = second - t.second;
	}
	else end.second = second - t.second;
	if (geon == true) minute -= 1;
	geon = false;
	if (minute < t.minute) {
		geon = true;
		minute += 60;
		end.minute = minute - t.minute;
	}
	else end.minute = minute - t.minute;
	if (geon == true) hour -= 1;
	end.hour = hour - t.hour;
	return end;
}
std::ostream& operator << (std::ostream& out, time& t) {
	out << t.hour << ":";
	if (t.minute < 10 && t.minute > -1) out << '0' << t.minute << ":";
	else out << t.minute << ":";
	if (t.second < 10 && t.minute > -1) out << '0' << t.second;
	else out << t.second;
	return out;
}
std::istream& operator >> (std::istream& in, time t) {
	return in; // 这里是求助的地方
}
void time::timer(void) {
	system("cls");
	while(true) {
		cout << *this;
		if (second > 0) second--;
		else
			if (minute > 0) {
				second += 59;
				minute--;
			}
			else
				if (hour > 0) {
					minute += 59;
					hour--;
				}
				else break;
		Sleep(1000);
		system("cls");
	}
	system("cls");
	cout << "Times up!\a";
	for (int i = 0; i < 15; ++i) cout << endl;
}
int main() {
	time test1;
	int h, m, s;
	cin >> h >> m >> s;
	test1.setTime(h, m, s);
	test1.timer();
	return 0;
}

刚刚学类,代码不好勿喷

2020/5/1 12:01
加载中...