试图重载==运算符,想要比较小时,分钟,秒变量,但是它们被声明为私有变量,并且被告知我们不允许调整头文件。如何在重载==运算符的代码中访问它们?我也无法访问它们,因为它们在setTime方法中被称为h,m,s。
// using _TIMEX_H_ since _TIME_H_ seems to be used by some C++ systems
#ifndef _TIMEX_H_
#define _TIMEX_H_
using namespace std;
#include <iostream>
class Time
{ public:
Time();
Time(int h, int m = 0, int s = 0);
void setTime(int, int, int);
Time operator+(unsigned int) const;
Time& operator+=(unsigned int);
Time& operator++(); // postfix version
Time operator++(int); // prefix version
// new member functions that you have to implement
Time operator-(unsigned int) const;
Time& operator-=(unsigned int);
Time& operator--(); // postfix version
Time operator--(int); // prefix version
bool operator==(const Time&) const;
bool operator<(const Time&) const;
bool operator>(const Time&) const;
private:
int hour, min, sec;
friend ostream& operator<<(ostream&, const Time&);
// new friend functions that you have to implement
friend bool operator<=(const Time&, const Time&);
friend bool operator>=(const Time&, const Time&);
friend bool operator!=(const Time&, const Time&);
friend unsigned int operator-(const Time&, const Time&);
};
#endif
.cpp文件
using namespace std;
#include <iostream>
#include <iomanip>
#include "Time.h"
Time::Time()
{ hour = min = sec = 0;
}
Time::Time(int h, int m, int s)
{ setTime(h, m, s);
}
void Time::setTime(int h, int m, int s)
{ hour = (h>=0 && h<24) ? h : 0;
min = (m>=0 && m<60) ? m : 0;
sec = (s>=0 && s<60) ? s : 0;
}
Time operator==(Time &t1, Time &t2)
{
return (t1.hour==t2.hour);
}
==
您应该实现的运算符是成员函数,因此您应该定义
bool Time::operator==(const Time& t) const
{
return hour == t.hour && min == t.min && sec == t.sec;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句