//// Created by Rdw on 2017/3/9.//#ifndef PROJECT5_TIME_H#define PROJECT5_TIME_H
class Time {
private:
int hour;
int minute;
public:
Time();//默認構造函數
Time(int h , int m);//構造函數
~Time();//析構函數void show() const;
void reset(int h , int m);
/*重載關係運算符*/
friend booloperator==(const Time &object1 , const Time &object2);
friend booloperator!=(const Time &object1 , const Time &object2);
friend booloperator<(const Time &object1 , const Time &object2);
};
#endif //PROJECT5_TIME_H
類的定義
//// Created by Rdw on 2017/3/9.//#include "Time.h"#include <iostream>usingnamespacestd;
Time::Time() {
}
Time::Time(int h, int m) {
hour = h;
minute = m;
}
Time::~Time() {
}
void Time::reset(int h, int m) {
hour = h;
minute = m;
}
void Time::show() const {
cout << hour << "hours " << minute << "minutes" << endl;
}
booloperator==(const Time &object1, const Time &object2) {
return (object1.hour == object2.hour && object1.minute == object2.minute);
}
booloperator!=(const Time &object1, const Time &object2) {
return !(object1 == object2);
}
booloperator<(const Time &object1, const Time &object2) {
int temp1 = object1.hour * 60 + object1.minute;
int temp2 = object2.hour * 60 + object2.minute;
return temp1 < temp2;
}
類的使用
#include <iostream>#include "Time.h"usingnamespacestd;
int main() {
Time time11 = Time(9 , 30);
Time time12 = Time(10 , 30);
Time time13 = Time(9 , 30);
if (time11 == time12)
cout << "OK!!!" << endl;
elsecout << "NOT OK!!!" << endl;
if (time11 < time12)
cout << "<" << endl;
elsecout << ">" << endl;
}
測試結果
E:\Project5\cmake-build-debug\Project5.exe
NOT OK!!!
<
Process finished withexit code 0