操作符重载实例

#include <ctime>
#include <iostream>

using namespace std;

class stopWatch{
public:
	stopWatch();
	void setTime(int newMin, int newSec);
	stopWatch operator - (stopWatch&);
	void showTime();
private:
	int min;
	int sec;
};

stopWatch::stopWatch(){
	min = 0;
	sec = 0;
}

void stopWatch::setTime(int newMin, int newSec){
	min = newMin;
	sec = newSec;
}

stopWatch stopWatch::operator-(stopWatch& anotherTime){
	stopWatch tempTime;
	int second;

	second = min * 60 + sec - (anotherTime.min * 60 + anotherTime.sec);
	if (second < 0){
		second = -second;
	}

	tempTime.min = second / 60;
	tempTime.sec = second % 60;
}

void stopWatch::showTime(){
	if (min > 0){
		cout << min << "minutes" << sec << "seconds\n";
	}
	else{
		cout << sec << "seconds\n";
	}
}

int main(){
	stopWatch startTime, endTime, usedTime;
	cout << "按回车键开始!";
	cin.get();

	time_t curtime = time(0); //获取当前系统时间
	tm tim = *localtime(&curtime); //根据当前时间获取当地时间
	int min, sec;
	min = tim.tm_min; //得到当前时间的分
	sec = tim.tm_sec;// 得到当前时间的秒
	startTime.setTime(min, sec);

	cout << "按回车键结束";
	cin.get();

	curtime = time(0); //获取当前系统时间
	tim = *localtime(&curtime); //根据当前时间获取当地时间
	min = tim.tm_min; //得到当前时间的分
	sec = tim.tm_sec;// 得到当前时间的秒
	endTime.setTime(min, sec);

	usedTime = endTime - startTime;
	cout << "用时";
	usedTime.showTime();

	return 0;
}

你可能感兴趣的:(操作符重载实例)