Chaz Chaz - 1 year ago 63
C++ Question

Accessing private variables of a class C++

Trying to overload the == operator, want to compare the hour, min, sec variables, but they're declared private and we've been told we're not allowed to adjust the header file. How do I access them in my code that is overloading the == operator? I also can't access them as h, m, s as they're called in the setTime method.

// 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(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;

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&);


.cpp file

using namespace std;

#include <iostream>
#include <iomanip>
#include "Time.h"

{ 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);

Answer Source

The == operator you're supposed to implement is a member function, so you should define

bool Time::operator==(const Time& t) const
    return hour == t.hour && min == t.min && sec == t.sec;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download