访问类C++的私有变量
问题描述:
试图重载==操作符,想要比较小时,分钟,秒变量,但它们被声明为私有变量,并且我们被告知我们不允许调整标题文件。如何在我的代码中访问它们以重载==运算符?我也无法将它们作为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);
}
答
这里有一个窍门:
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在您的运营商==功能中使用您的私人字段。但是因为你的操作符!=被定义为朋友,所以你可以在那里做。
'Time Time :: operator ==(Time&t1,Time&t2)'会做。你错过了一些东西。 – DeiDei
你的'operator =='在h文件和cpp文件中是不一样的。您应该将cpp文件调整为您的h文件。 –