2016-11-18 167 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