请教c++运算符重载程序报错原因

来源:百度知道 编辑:UC知道 时间:2024/05/21 09:22:03
以下程序中重载流操作和自增操作符是友元函数,为什么编译报错:
error C2248: 'hour' : cannot access private member declared in class 'Time'
#include<iostream>
#include<iomanip>
using namespace std;
class Time
{
int hour,minute,second;
public:
void set(int h,int m,int s){hour=h;minute=m;second=s;}
friend Time& operator++(Time& a);
friend Time operator++(Time& a,int);
friend ostream& operator<<(ostream& o,const Time& t);
};
Time& operator++(Time& a)
{
if(!(a.second=(a.second+1)%60)&&!(a.minute=(a.minute+1)%60))
a.hour=(a.hour+1)%24;
return a;
}
Time operator++(Time& a,int)
{
Time t(a);
if(!(a.second=(a.second+1)%60)&&!(a.minute=(a.minute+1)%60))
a.hour=(a.hour+1)%24;
return t;
}
ostream& operator<<(ostream& o,const Time& t)
{
return o<<setfill('0')<<setw(2)<<t.hour<<":"<<setw(2)<<

这可能是编译器的原因。
有些低版本的编译器,除了在类中申明友元关系之外,还要在类定义前对函数进行前向声明。如:
Class Time;
Time& operator++(Time& a);
Time operator++(Time& a,int);
ostream& operator<<(ostream& o,const Time& t);
如果你用的是vc6.0的话就会出现这种情况。
虽然重载运算符很方便,但在访问类私有成员的时候,除非关系密切或者经常访问,不然还是通过函数来访问类的私有成员比较好。

不能直接访问对象的私有成员,而是因该通过公有成员函数作为接口访问

类中加一个函数
int getsecond()
{
return second;
}
想提取second的值得话t.getsecond()就可以了
其他依此类推gethour()....