关系运算符重载
类的声明
#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
bool operator==(
const Time &object1 ,
const Time &object2);
friend
bool operator!=(
const Time &object1 ,
const Time &object2);
friend
bool operator<(
const Time &object1 ,
const Time &object2);
};
#endif //PROJECT5_TIME_H
类的定义
#include "Time.h"
#include <iostream>
using namespace std;
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;
}
bool operator==(
const Time &object1,
const Time &object2) {
return (object1.hour == object2.hour && object1.minute == object2.minute);
}
bool operator!=(
const Time &object1,
const Time &object2) {
return !(object1 == object2);
}
bool operator<(
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"
using namespace std;
int main() {
Time time11 = Time(
9 ,
30);
Time time12 = Time(
10 ,
30);
Time time13 = Time(
9 ,
30);
if (time11 == time12)
cout <<
"OK!!!" << endl;
else
cout <<
"NOT OK!!!" << endl;
if (time11 < time12)
cout <<
"<" << endl;
else
cout <<
">" << endl;
}
测试结果
E:\Project5\cmake-build-debug\Project5.exe
NOT OK!!!
<
Process finished
with exit code
0
转载请注明原文地址: https://ju.6miu.com/read-12882.html