访问类C ++的私有变量

时间:2016-11-18 10:04:38

标签: c++

尝试重载==运算符,想要比较小时,分钟,秒变量,但是它们被声明为私有,我们被告知我们不允许调整头文件。如何在我的重载==运算符的代码中访问它们?我也无法将它们作为h,m,s访问它们,因为它们是在setTime方法中调用的。

// 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);
}

2 个答案:

答案 0 :(得分:2)

您应该实施的==运算符是成员函数,因此您应该定义

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

答案 1 :(得分: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;
}

您无法访问operator ==函数中的私有字段。但由于你的操作员!=被定义为朋友,你可以在那里做。