試圖重載==操作符,想要比較小時,分鐘,秒變量,但它們被聲明爲私有變量,並且我們被告知我們不允許調整標題文件。如何在我的代碼中訪問它們以重載==運算符?我也無法將它們作爲h,m,s來訪問,因爲它們是在setTime方法中調用的。訪問類C++的私有變量
// 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);
}
'Time Time :: operator ==(Time&t1,Time&t2)'會做。你錯過了一些東西。 – DeiDei
你的'operator =='在h文件和cpp文件中是不一樣的。您應該將cpp文件調整爲您的h文件。 –