2016-11-18 114 views
-2

試圖重載==操作符,想要比較小時,分鐘,秒變量,但它們被聲明爲私有變量,並且我們被告知我們不允許調整標題文件。如何在我的代碼中訪問它們以重載==運算符?我也無法將它們作爲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); 
} 
+0

'Time Time :: operator ==(Time&t1,Time&t2)'會做。你錯過了一些東西。 – DeiDei

+1

你的'operator =='在h文件和cpp文件中是不一樣的。您應該將cpp文件調整爲您的h文件。 –

回答

2

你應該實現==運營商是一個成員函數,所以你應該定義

bool Time::operator==(const Time& t) const 
{ 
    return hour == t.hour && min == t.min && sec == t.sec; 
} 
+0

如何訪問t.hour? – cokceken

+0

這是一個成員函數。你寫「t.hour」。 – molbdnilo

+0

所以你可以說這個 - >小時,但你不能說t.hour。假設我爲某個其他類重載了==運算符。我可以訪問他們的私有變量嗎? – cokceken

0

這裏有一個竅門:

bool operator==(Time &t1, Time &t2) 
{ 
    return !(t1 != t2); 
} 
bool operator!=(const Time& t1, const Time& t2) 
{ 
    return t1.hour != t2.hour || t1.min != t2.min || t1.sec != t2.sec; 
} 

你不能acc在您的運營商==功能中使用您的私人字段。但是因爲你的操作符!=被定義爲朋友,所以你可以在那裏做。

+0

你不能訪問t2.hour它是私人的 – cokceken

+0

是的,你不能在函數運算符==中訪問它,但你可以在函數運算符中訪問它!= – Michael

+0

沒有必要實現一個非成員'operator ==' - 已經有一個'operator =='成員。整個頭文件設計的很糟糕。 'operator =='和'operator <'應該是非會員朋友。所有其他的比較應該是非成員在這兩方面的定義,並不需要成爲朋友。例如:'operator>'返回'rhs